views:

3725

answers:

4

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?

+8  A: 

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])) ?>
Paolo Bergantino
Thanks Paolo, This worked a treat!
Matthew James Taylor
+1  A: 

you can format the date in your mysql using the date_format function. This site will help you format the date http://www.mysqlformatdate.com

gerard
+1  A: 

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';
}
Newmania
why not escape T sign ... and the !$time condition is not necesary, as current time is used when no time parameter is given or null:date('Y-m-d\TH:i:s\Z', $time);//Z represents current time zone
gregor