So you have a date from your database and it looks like this: 2014-01-31 01:02:03. It so happens that your server is on UTC time. You want to:
- Format the date into something prettier, and
- Offset the date so it’s adjusted for a user’s local time zone.
Ok, great. You only have to SUFFER THE PAIN OF A THOUSAND MIGRAINES AND oh wait it’s actually sort of easy. But man, this took a lot of pain and searching to find. The key is moment.js, a glorious gift to developer-kind.
So the way I’m doing this is to create an HTML5 <time> element, but it can certainly be done other ways. First, after running a DB query, I have PHP produce this:
<time datetime="2014-01-03 12:57:03"> 2014-01-03 12:57:03 </time>
Not very pleasant to look at. So then we do a little moment.js…
var date = $(time).attr('datetime'); var newformat =
'D MMM YYYY [at] h:mm A'; var nice = moment(date, 'YYYY-MM-DD HH:mm:ss').format(new_format); $('time').html(nice);
There’s some jQuery in there, too, but it isn’t necessary.
What we just did, is we read the date from our <time> element’s datetime attribute, then told moment what format it was in, so it could then spit it back out how we want it to, using .format(), as the human-readable part of the <time> element.
The result looks like this: 3 Jan 2014 at 12:57 PM. Yay. It’s nicer. But that’s still UTC time, and no timezone data was saved in our DB. So we have to add it.
<time datetime="2014-01-03 12:57:03 +0000"> 2014-01-03 12:57:03 UTC </time>
var nice = moment(date,'YYYY-MM-DD HH:mm:ss ZZ').format(newformat);
See the “ZZ” we added in the middle? Now moment.js knows we have a timezone and what it is. And just like that, it’s been adjusted: 2 Jan 2014 at 5:57 PM (adjusted for America/Denver, -7:00).
It was so easy, that after all the suffering gone through before this point, I’m almost mad. But not really. But just a little bit.