DateTime Timestamp Parsing

As part of a recent project, I was tasked with taking timestamps returned by an API and displaying fuzzy dates in the final output (e.g. 3hrs ago, in 2 weeks, tomorrow).

Note: as pointed out by the author of the DateTime extension (Derick Rethans) in the comments, you don’t need to use DateTime::createFromFormat() for the ATOM format. The DateTime constructor works like strtotime() and can cope with all the formats it can. However, I still want to point out how to use DateTime::createFromFormat(), so I’m not changing this post.

The timestamp format in question looks like: 2012-09-01T16:20:01-05:00

This format can be found in PHP as the DATE_ATOM or DateTime::ATOM constants, which contain the date() formatter string: Y-m-d\TH:i:sP

With this in hand, we can now easily parse the timestamp into a useful object:

$dateTime = DateTime::createFromFormat(DateTime::ATOM, "2012-09-01T16:20:01-05:00");

Doing a var_dump() of the $dateTime variable we can now see that we get:

With this DateTime object we can now do all kinds of magic, like changing the timezone:

(If you are wondering about the timezone, the UK is currently on BST (British Summer Time), which is +1 UTC.)

We can also do interval math:

That’s kinda mundane though, lets try something a little tricker:

The DateTime extension is really versatile if you’re working with dates (or times, hah!), and so much easier than doing timestamp math!

Update: several people have asked me to show the fuzzy date stuff, so here is a gist.

Usage looks like this:

2 Responses to “DateTime Timestamp Parsing”

  1. Hi!

    You don’t actually have to use createFromFormat() here as PHP’s Date/Time parser understands this format just fine:

    derick@whisky:~$ php -r 'var_dump(date_create("2012-09-01T16:20:01-05:00"));'
    object(DateTime)#1 (3) {
      ["date"]=>
      string(19) "2012-09-01 16:20:01"
      ["timezone_type"]=>
      int(1)
      ["timezone"]=>
      string(6) "-05:00"
    }
    
  2. [...] a new post to his blog Davey Shafik looks at parsing dates with DateTime, the new and improved way to handle dates in PHP (well, not so new but definitely improved). As [...]

Twitter

“@Harris_Bryan: Georgia Tech is offering a 100% online masters for $6,000!! http://t.co/IUdZgmCOad” - the closing is food for thought...

@dshafik [7 hours ago]

@ChiperSoft aaaah, ours is 8-7:30 or later. That came at about 10 months too. Also wife gets up early, I sleep in. Except sunday. :D

@dshafik [19 hours ago]

@dshafik oh she mostly sleeps through the night, but she wakes up at 6am, and we both like 8hrs of sleep :)

@ChiperSoft [19 hours ago]

@dshafik: I'm on IRC :-/

@derickr [19 hours ago]

Books & Things

Search

Archives

Tags