I'm trying to display a datetime from my MySQL database as an iso 8601 formated string with PHP but it's coming out wrong.
17 Oct 2008 is coming out as: 1969-12-31T18:33:28-06:00 which is clearly not correct (the year should be 2008 not 1969)
This is the code I'm using:
<?= date("c", $post[3]) ?>
$post[3] is the datetime (CURRENT_TIMESTAMP) from my MySQL database.
Any ideas what's going wrong?
The second argument of date is a UNIX timestamp, not a database timestamp string.
You need to convert your database timestamp with strtotime.
<?= date("c", strtotime($post[3])) ?>
Using the DateTime class available in PHP version 5.2 it would be done like this:
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
As of PHP 5.4 you can do this as a one-liner:
echo (new DateTime('17 Oct 2008'))->format('c');
Procedural style :
echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Object oriented style :
$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 1 :
echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 2 :
echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00
Notes :
1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.
2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :
echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00
3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :
echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00
For pre PHP 5:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
Here is the good function for pre PHP 5:
I added GMT difference at the end, it's not hardcoded.
function iso8601($time=false) {
if ($time === false) $time = time();
$date = date('Y-m-d\TH:i:sO', $time);
return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}
The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:
// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z
// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z
// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z
//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z
Related
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.
Do you know how I can convert this to a strtotime, or a similar type of value to pass into the DateTime object?
The date I have:
Mon, 12 Dec 2011 21:17:52 +0000
What I've tried:
$time = substr($item->pubDate, -14);
$date = substr($item->pubDate, 0, strlen($time));
$dtm = new DateTime(strtotime($time));
$dtm->setTimezone(new DateTimeZone(ADMIN_TIMEZONE));
$date = $dtm->format('D, M dS');
$time = $dtm->format('g:i a');
The above is not correct. If I loop through a lot of different dates its all the same date.
You don't need to turn the string into a timestamp in order to create the DateTime object (in fact, its constructor doesn't even allow you to do this, as you can tell). You can simply feed your date string into the DateTime constructor as-is:
// Assuming $item->pubDate is "Mon, 12 Dec 2011 21:17:52 +0000"
$dt = new DateTime($item->pubDate);
That being said, if you do have a timestamp that you wish to use instead of a string, you can do so using DateTime::setTimestamp():
$timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
$dt = new DateTime();
$dt->setTimestamp($timestamp);
Edit (2014-05-07):
I actually wasn't aware of this at the time, but the DateTime constructor does support creating instances directly from timestamps. According to this documentation, all you need to do is prepend the timestamp with an # character:
$timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
$dt = new DateTime('#' . $timestamp);
While #drrcknlsn is correct to assert there are multiple ways to convert a time string to a datatime, it's important to realize that these different ways don't deal with timezones in the same way.
Option 1 : DateTime('#' . $timestamp)
Consider the following code :
date_format(date_create('#'. strtotime('Mon, 12 Dec 2011 21:17:52 +0800')), 'c');
The strtotime bit eliminates the time zone information, and the date_create function assumes GMT.
As such, the output will be the following, no matter which server I run it on :
2011-12-12T13:17:52+00:00
Option 2 : date_create()->setTimestamp($timestamp)
Consider the following code :
date_format(date_create()->setTimestamp(strtotime('Mon, 12 Dec 2011 21:17:52 +0800')), 'c');
You might expect this to produce the same output. However, if I execute this code from a Belgian server, I get the following output :
2011-12-12T14:17:52+01:00
Unlike the date_create function, the setTimestamp method assumes the time zone of the server (CET in my case) rather than GMT.
Explicitly setting your time zone
If you want to make sure your output matches the time zone of your input, it's best to set it explicitly.
Consider the following code :
date_format(date_create('#'. strtotime('Mon, 12 Dec 2011 21:17:52 +0800'))->setTimezone(new DateTimeZone('Asia/Hong_Kong')), 'c')
Now, also consider the following code :
date_format(date_create()->setTimestamp(strtotime('Mon, 12 Dec 2011 21:17:52 +0800'))->setTimezone(new DateTimeZone('Asia/Hong_Kong')), 'c')
Because we explicitly set the time zone of the output to match that of the input, both will create the same (correct) output :
2011-12-12T21:17:52+08:00
Probably the simplest solution is just:
DateTime::createFromFormat('U', $timeStamp);
Where 'U' means Unix epoch. See docs: http://php.net/manual/en/datetime.createfromformat.php
This is my solution:
function changeDateTimezone($date, $from='UTC', $to='Asia/Tehran', $targetFormat="Y-m-d H:i:s") {
$date = new DateTime($date, new DateTimeZone($from));
$date->setTimeZone(new DateTimeZone($to));
return $date->format($targetFormat);
}
I try to calculate the easter date in php.
echo(date("2012: t.n.Y", easter_date(2012)).'<br>'); // 2012: 30.4.2012
This date is correct for the eastern orthodox churches. But I want the normal one!
My next try with the easter_days function:
function easter($year) {
$date = new DateTime($year.'-03-21');
$date->add(new DateInterval('P'.easter_days($year).'D'));
echo $year.": ".$date->format('t.m.Y') . "<br>\n";
}
easter(2012); // 2012: 30.4.2012
Tested oh PHP 5.2.6 and 5.3.6. I also tried to change the timezone with no success.
Your date format is wrong. t is the number of days in the given month (april = 30). Use d for day of the month:
echo(date("d.m.Y", easter_date(2012)).'<br>');
// will output: 08.04.2012
btw: orthodox easter date is April 15th this year.
If you want to use the DateTime class, the following will give you a DateTime object set to Easter. Use easter_date() instead of fiddling around with easter_days():
function easter($year, $format = 'd.m.Y') {
$easter = new DateTime('#' . easter_date($year));
// if your timezone is already correct, the following line can be removed
$easter->setTimezone(new DateTimeZone('Europe/Berlin'));
return $easter->format($format);
}
echo easter(2012); // 08.04.2012
echo easter(2012, 'd.m.Y H:i'); // 08.04.2012 00:00
Timezone
Setting the timezone is only necessary when the default timezone is wrong. Must be set afterwards as it is ignored in the constructor when a unix timestamp is provided.
If left out, the DateTime constructor may produce a wrong date (e.g. 07.04.2012 22:00 for 2012 instead of 08.04.2012 00:00)
I have a year (2002) and I'm trying to get it into the following format:
2002-00-00T00:00:00
I tried various iterations, the last of which was this:
$testdate = DateTime::createFromFormat(DateTime::ISO8601, date("c"))
echo date_format($testdate, '2002');
But, even if I come close, it always seems to add +00:00 to the end of it...
The 'c' format in PHP always appends the timezone offset. You can't avoid that. But you can build the date yourself from components:
date('Y-m-d\TH:i:s', $testdate);
Best way is to use constants (PHP 5 >= 5.5.0, PHP 7)
date(DATE_ISO8601, $timeToChange);
Docs:
http://php.net/manual/en/class.datetimeinterface.php#datetime.constants.types
The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:
// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z
// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z
// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z
//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z
Previous published: https://stackoverflow.com/a/61796705/5898408
date('Y-m-d\TH:i:s\Z', time() - date('Z'));