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:
This format can be found in PHP as the
DateTime::ATOM constants, which contain the
date() formatter string:
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");
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”
@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]