How do I get timestamp from e.g. 22-09-2008?
This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.
If you don't care about timezone, or want to use the time zone your server uses:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324 (This will differ depending on your server time zone...)
If you want to specify in which time zone, here EST. (Same as New York.)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093305
Or if you want to use UTC. (Same as "GMT".)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093289
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
There is also strptime() which expects exactly one format:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
Warnings:
This function is not implemented on Windows
This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.
With DateTime API:
$dateTime = new DateTime('2008-09-22');
echo $dateTime->format('U');
// or
$date = new DateTime('2008-09-22');
echo $date->getTimestamp();
The same with the procedural API:
$date = date_create('2008-09-22');
echo date_format($date, 'U');
// or
$date = date_create('2008-09-22');
echo date_timestamp_get($date);
If the above fails because you are using a unsupported format, you can use
$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U');
// or
$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');
Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.
Yet another alternative is to use the IntlDateFormatter API:
$formatter = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'GMT',
IntlDateFormatter::GREGORIAN,
'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');
Unless you are working with localized date strings, the easier choice is likely DateTime.
Be careful with functions like strtotime() that try to "guess" what you mean (it doesn't guess of course, the rules are here).
Indeed 22-09-2008 will be parsed as 22 September 2008, as it is the only reasonable thing.
How will 08-09-2008 be parsed? Probably 09 August 2008.
What about 2008-09-50? Some versions of PHP parse this as 20 October 2008.
So, if you are sure your input is in DD-MM-YYYY format, it's better to use the solution offered by #Armin Ronacher.
This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.
If you don't care about timezone, or want to use the time zone your server uses:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324 (This will differ depending on your server time zone...)
If you want to specify in which time zone, here EST. (Same as New York.)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093305
Or if you want to use UTC. (Same as "GMT".)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093289
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
Using mktime:
list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);
Using strtotime() function you can easily convert date to timestamp
<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');
//define date and time
$date = date("d M Y H:i:s");
// output
echo strtotime($date);
?>
More info: http://php.net/manual/en/function.strtotime.php
Online conversion tool: http://freeonlinetools24.com/
Here is a very simple and effective solution using the split and mtime functions:
$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date);
//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);
It worked like a charm for me.
Use PHP function strtotime()
echo strtotime('2019/06/06');
date — Format a local time/date
Given that the function strptime() does not work for Windows and strtotime() can return unexpected results, I recommend using date_parse_from_format():
$date = date_parse_from_format('d-m-Y', '22-09-2008');
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);
If you know the format use strptime because strtotime does a guess for the format, which might not always be correct. Since strptime is not implemented in Windows there is a custom function
http://nl3.php.net/manual/en/function.strptime.php#86572
Remember that the returnvalue tm_year is from 1900! and tm_month is 0-11
Example:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)
If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat():
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22
It's obvious in this case, but e.g. 03-04-2008 could be 3rd of April or 4th of March depending on where you come from :)
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
http://php.net/manual/en/function.date.php
$time = '22-09-2008';
echo strtotime($time);
function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = "#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$#is" ) {
$return = false;
$_timezone = date_default_timezone_get();
date_default_timezone_set( $timezone );
if( preg_match( $expression, $date, $matches ) )
$return = date( "Y-m-d " . ( $slash_time ? '00:00:00' : "h:i:s" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date("h:i:s") ) );
date_default_timezone_set( $_timezone );
return $return;
}
// expression may need changing in relation to timezone
echo date_to_stamp('19/03/1986', false) . '<br />';
echo date_to_stamp('19**03**1986', false) . '<br />';
echo date_to_stamp('19.03.1986') . '<br />';
echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';
echo date('Y-m-d h:i:s') . '<br />';
//1986-03-19 02:37:30
//1986-03-19 02:37:30
//1986-03-19 00:00:00
//1986-03-19 05:37:30
//2012-02-12 02:37:30
<?php echo date('U') ?>
If you want, put it in a MySQL input type timestamp. The above works very well (only in PHP 5 or later):
<?php $timestamp_for_mysql = date('c') ?>
Here is how I'd do it:
function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')
{
//returns an array containing day start and day end timestamps
$old_timezone=date_timezone_get();
date_default_timezone_set($timezone);
$date=strptime($date,$format);
$day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));
$day_end=$day_start+(60*60*24);
date_default_timezone_set($old_timezone);
return array('day_start'=>$day_start, 'day_end'=>$day_end);
}
$timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');
$day_start=$timestamps['day_start'];
This way, you let the function know what date format you are using and even specify the timezone.
If you already have the date in that format, you only need to call the "strtotime" function in PHP.
$date = '22-09-2008';
$timestamp = strtotime($date);
echo $timestamp; // 1222041600
Or in a single line:
echo strtotime('22-09-2008');
Short and simple.
For PHP >=5.3, 7 & 8 the this may work-
$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format.
//just need to keep in mind that date and format matches.
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp
$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.
Docs:
date_parse_from_format()
mktime()
date()
Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to timestamp using strtotime. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.
Please see this example: https://3v4l.org/BRlmV
function getthistime($type, $modify = null) {
$now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));
if($modify) {
$now->modify($modify);
}
if(!isset($type) || $type == 'datetime') {
return $now->format('Y-m-d H:i:s');
}
if($type == 'time') {
return $now->format('H:i:s');
}
if($type == 'timestamp') {
return $now->getTimestamp();
}
}
function timestampfromdate($date) {
return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();
}
echo getthistime('timestamp')."--".
timestampfromdate(getthistime('datetime'))."--".
strtotime(getthistime('datetime'));
//getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)
//getthistime('timestamp') == strtotime(getthistime('datetime')) (false)
I have used this format:
$presentDateTime = strtotime(date('Y-m-d H:i:s'));
If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z) to timestamp, here's how you'd do it:
function UTCToTimestamp($utc_datetime_str)
{
preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
$datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];
return strtotime($datetime_str);
}
$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);
I have a string: 30/06/18 (30th June 2018)
I am converting to a date:
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18')->format('d-m-Y');
echo $calcFieldDate;
Result: 18-06-2018
Now I want to add 20 days to the date:
$expiryDate = date("d-m-Y", strtotime("+20 days", $calcFieldDate));
echo $expiryDate;
Expected Result: 08-07-2018
Actual Result: 31-01-1970
I am obviously creating a date format which is then subsequently being treated as a string...
Every time I try a conversion, I just hit another road block - is there anyway to create a date that is then treated like a date?
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18')->format('d-m-Y');
echo $calcFieldDate;
Result:30-06-2018
$expiryDate = date("d-m-Y", strtotime("+20 days", strtotime($calcFieldDate)));
echo $expiryDate;
Result:20-07-2018
Strtotime() The second parameter is the timestamp
You actually don't need to revert using strtotime and date functions, you can actually use DateTime to simply add dates into it:
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18');
echo $calcFieldDate->format('d-m-Y'); // get inputted date
$expiryDate = clone $calcFieldDate; // clone the original date object
$expiryDate->modify('+20 days'); // adjust the cloned date
echo $expiryDate->format('d-m-Y'); // show the adjusted date
This will sort your problem.
$str="30/06/18 (30th June 2018)";
$arr_temp=explode(" ",$str);
$str_date=str_replace("/","-",$arr_temp[0]);
$dt = DateTime::createFromFormat('d-m-y',$str_date);
$date=$dt->format('d-m-Y');
$new_date=date('d-m-Y',strtotime("+20 days",strtotime($date)));
echo $new_date;
How do I convert 2014-10-10 04:13:24 to 2014-10-10T04:13:24+00:00 in php or mysql
The above mentioned date is for xml format in sitemaps
For reference check Q: How do I compute lastmod date? (Sitemaps.org FAQ)
code which i have tried:
echo "GIVEN DATE ".$timestamp = "2014-10-10 04:13:24";
echo "<br>";
$year = date('Y',strtotime($timestamp)).";
$month = date('m',strtotime($timestamp)).";
$day = date('d',strtotime($timestamp))."";
echo '<br>';
$hour = date('H',strtotime($timestamp))."";
$minutes = date('i',strtotime($timestamp))."";
$seconds = date('s',strtotime($timestamp))."<br>";
$gmktime= gmmktime($hour,$minutes,$seconds,$month,$day,$year)."<br>";
echo "output date".$isodate = date('c', $gmktime);
is the above out put conversion correct?
**OUTPUT**
GIVEN DATE : 2014-10-10 04:13:24
output date : 2014-10-10T06:13:24+02:00
Your output is correct in the light of the Sitemaps.org spec. "2014-10-10T06:13:24+02:00" is the same date/time as "2014-10-10T04:13:24+00:00".
Learn more about the W3C Datetime encoding which is used by Sitemaps.org.
Also, don't solve this with date functions, solve this with string function / operations: You change a single byte inside a string at a fixed position and then you append a string:
$timestamp = "2014-10-10 04:13:24";
$timestamp[10] = "T";
$timestamp .= "+00:00";
echo $timestamp, "\n"; // 2014-10-10T04:13:24+00:00
Or if you like to save some bytes in your file use "Z" instead of "+00:00" to denote the timezone:
$timestamp = "2014-10-10 04:13:24";
$timestamp[10] = "T";
$timestamp .= "Z";
echo $timestamp, "\n"; // 2014-10-10T04:13:24Z
PHP 5:
<?php
// Set the default timezone
date_default_timezone_set('UTC');
// Get Unix timestamp for a date
// Reference: mktime(hour, minute, second, month, day, year)
$time = mktime(04, 13, 24, 10, 10, 2014);
// Alternatively (must be a valid English date format)
$time = strtotime('2014-10-10 04:13:24');
// ISO 8601 date (added in PHP 5)
$isodate = date('c', $time);
echo $isodate; // 2014-10-10T04:13:24+00:00
// RFC 2822 formatted date
$rfcdate = date('r', $time);
echo $rfcdate; // Fri, 10 Oct 2014 04:13:24 +0000
?>
References:
date() / gmdate()
mktime() / gmmktime()
strtotime() : Supported Date and Time Formats
date_default_timezone_set() : List of Supported Timezones
ISO 8601
RFC 2822
In PHP
In PHP you use strptime() to parse the time and turn it into a structured array. Then pass the results of that into the mktime() function to get a UNIX timestamp.
In MySQL
Use UNIX_TIMESTAMP
SELECT UNIX_TIMESTAMP(datetime_column) FROM table;
I want to convert 1373892900000 to Monday 2013/07/15 8:55 AM in Codeigniter.
However, I keep receiving a totally different result by converting the timestamp using the function i have written, please note:I need to change the dates according to different timezones, that is why I want to write it this way:
public function time_convert($timestamp){
$this->load->helper('date');
date_default_timezone_set('UTC');
$daylight_saving = TRUE;
$timezone = "UM4"; //toronto or new york timezone
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$final_time = standard_date('DATE_RFC822', $time);
return $final_time;
}
Result from the above function is: Sat, 08 Dec 06 01:40:00 +0000
And if I don't put date_default_timezone_set('UTC'); in the above function, I get this date instead Sat, 08 Dec 06 02:40:00 +0100. My codeigniter seems to default the timezone to Europe/Berlin.
Can anyone please help me correct any of the mistakes I might have made?
Why not just use PHP's date function?
public function time_convert($timestamp){
return date('l Y/m/d H:i', $timestamp);
}
For different timezones use a DateTime object:
public function time_convert($timestamp, $timezone = 'UTC'){
$datetime = new DateTime($timestamp, new DateTimeZone($timezone));
return $datetime->format('l Y/m/d H:i');
}
Think that should work. Note: I tihnk you need at least PHP version 5.20 for the TimeZone class.
<?php
$time_str=1373892900000;
echo gmdate("fill with your format", $time_str);
?>
your format = format your time in php, reading this page for details.
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.gmdate.php
Appears as though an invocation of standard_date with the DATE_ATOM format may sort you:
echo unix_to_human(time(), true, 'us'); # returns 2013-07-12 08:01:02 AM, for example
There are a whole host of other options for the format, enumerated on the linked page.
This how to covert timestamp to date very simple:
echo date('m/d/Y', 1299446702);
to convert timestamp to human readable format try this:
function unix_timestamp_to_human ($timestamp = "", $format = 'D d M Y - H:i:s')
{
if (empty($timestamp) || ! is_numeric($timestamp)) $timestamp = time();
return ($timestamp) ? date($format, $timestamp) : date($format, $timestamp);
}
$unix_time = "1251208071";
echo unix_timestamp_to_human($unix_time); //Return: Tue 25 Aug 2009 - 14:47:51
if you want to convert it to a format like this: 2008-07-17T09:24:17Z than use this method
<?php
$timestamp=1333699439;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
for details about date:
http://php.net/manual/en/function.date.php
Your timestamp is coming from javascript on the client, I would guess, because it appears to be in milliseconds. php timestamps are in seconds. So to get the answer you want, first divide by 1000.
Showing the full year would have made the issue more obvious, as you would have seen the year as 45,506.
My $date output is in the foreach loop
09/25/11, 02/13/11, 09/15/10, 06/11/10, 04/13/10, 04/13/10, 04/13/10,
09/24/09, 02/19/09, 12/21/08
My mysql query(PHP) is as follows
("INSERT INTO table_name(`field1`, `field2`,`date`) VALUES ('".$value1."','".$value2 ."','".$date."')");
Question: In my database all the dates stores as 0000-00-00 00:00:00. But 4th date (06/11/10) is stored as 2006-11-10 00:00:00.
I tried with date('Y-m-d H:i:s', $date); but no help.
Note: My database field is datetime type.
Any idea?
You're on the right track with your date('Y-m-d H:i:s',$date); solution, but the date() function takes a timestamp as its second argument, not a date.
I'm assuming your examples are in American date format, as they look that way. You can do this, and it should get you the values you're looking for:
date('Y-m-d H:i:s', strtotime($date));
The reason it's not working is because it expects the date in the YYYY-MM-DD format, and tries to evaluate your data as that. But you have MM/DD/YY, which confuses it. The 06/11/10 example is the only one that can be interpreted as a valid YYYY-MM-DD date out of your examples, but PHP thinks you mean 06 as the year, 11 as the month, and 10 as the day.
I created my own function for this purpose, may be helpful to you:
function getTimeForMysql($fromDate, $format = "d.m.y", $hms = null){
if (!is_string($fromDate))
return null ;
try {
$DT = DateTime::createFromFormat($format, trim($fromDate)) ;
} catch (Exception $e) { return null ;}
if ($DT instanceof DateTime){
if (is_array($hms) && count($hms)===3)
$DT->setTime($hms[0],$hms[1],$hms[2]) ;
return ($MySqlTime = $DT->format("Y-m-d H:i:s")) ? $MySqlTime : null ;
}
return null ;
}
So in your case, you use format m/d/yy :
$sql_date = getTimeForMysql($date, "m/d/yy") ;
if ($sql_date){
//Ok, proceed your date is correct, string is returned.
}
You don't have the century in your date, try to convert it like this:
<?php
$date = '09/25/11';
$date = DateTime::createFromFormat('m/d/y', $date);
$date = $date->format('Y-m-d');
print $date;
Prints:
2011-09-25
Now you can insert $date into MySQL.