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-dTH: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:

Comments
  • Derick Rethans
    Posted September 20, 2011 3:24 am 0Likes

    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"
    }
    
  • Trackback: PHPDeveloper.org: Davey Shafik's Blog: DateTime Timestamp Parsing

Comments are closed.