Organizational Research By

Surprising Reserch Topic

how to display a date as iso 8601 format with php


how to display a date as iso 8601 format with php  using -'php,mysql,datetime,iso8601'

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?
    

asked Sep 29, 2015 by santosh soni
0 votes
7 views



Related Hot Questions

4 Answers

0 votes

The second argument of date is a UNIX timestamp, not a database timestamp string.

You need to convert your database timestamp with strtotime.


answered Sep 29, 2015 by ashishshukla
0 votes

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');

See it in action

As of PHP 5.4 you can do this as a one-liner:

echo (new DateTime('17 Oct 2008'))->format('c');
answered Sep 29, 2015 by akhilesh
0 votes

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';
}
answered Sep 29, 2015 by manju bhargava
0 votes

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));
}
answered Sep 29, 2015 by ashishshukla

...