How do I convert an ISO8601 date to another format in PHP?
Asked Answered
B

2

8

Facebook outputs dates in ISO8601 format - e.g.: 2011-09-02T18:00:00

Using PHP, how can I reformat into something like: Friday, September 2nd 2011 at 6:00pm

Nb - I was doing it in Javascript, but IE has date bugs so I want a cross-browser solution.

Barkentine answered 23/6, 2011 at 18:3 Comment(0)
C
15

A fast but sometimes-unreliable solution:

$date = '2011-09-02T18:00:00';

$time = strtotime($date);

$fixed = date('l, F jS Y \a\t g:ia', $time); // 'a' and 't' are escaped as they are a format char.

Format characters detailed here.

Crony answered 23/6, 2011 at 18:12 Comment(2)
strtotime is magical, but not omniscient. '01-02-03' will probably parse wrong, since it's utterly non-obvious which is Y, M, or D. In this case, the date string is a well-documented format, so not going to be an issue. But relying on strtotime to be always right is a bad way to go.Crony
On testing - the 't' also needs to be prefixed with an '\' escape char. (just in case anyone should ever have the same problem :-)Barkentine
N
1

Converting from ISO 8601 to unixtimestamp :

strtotime('2012-01-18T11:45:00+01:00');
// Output : 1326883500

Converting from unixtimestamp to ISO 8601 (timezone server) :

date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
// Output : 2012-01-18T11:45:00+01:00

Converting from unixtimestamp to ISO 8601 (GMT) :

date_format(date_create('@'. 1326883500), 'c') . "\n";
// Output : 2012-01-18T10:45:00+00:00

Converting from unixtimestamp to ISO 8601 (custom timezone) :

date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2012-01-18T05:45:00-05:00
Nissie answered 3/4, 2017 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.