Viewed   92 times

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.



A fast but sometimes-unreliable solution:

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

$time = strtotime($date);

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

Format characters detailed here.

Monday, August 1, 2022

ffmpeg is a great library for this sort of thing. Here's a walkthrough of the process:

Saturday, August 6, 2022

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

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);
Saturday, November 5, 2022

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601


For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));
Saturday, August 6, 2022

Use the pandas datetools parser to parse the date and then format it using the standard python strftime function.

>>> df['q_date'].apply(
        lambda x: pd.datetools.parse(x).strftime('%Y-%m-%dT%H:%M%:%SZ'))
0    20120210T00:0000Z
1    20120210T00:0000Z
2    20120210T00:0000Z
3    20120210T00:0000Z
4    20120210T00:0000Z
Name: q_date, dtype: object
Tuesday, December 27, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :