(Almost) Proper Cross-Browser Timestamps
Tuesday, September 9 2014
While making this blog, one of the things I had to do was figure out a way to represent post timestamps. These are used not only for sorting and filtering posts by date, but to display the date a post was written in a pretty, human-readable format.
My current system is pretty simple. I have automated the creation of new posts in Markdown via a Python script, which injects the current time as a timestamp in an HTML comment. When the blog is built, the same Python script parses the comment and aggregates post information into a JSON file, which Angular can then request and use. The timestamp is available as the string
post.date, and displaying the date nicely is as simple as
post.date | date:'EEEE, MMMM d y' (using Angular’s date filter).
The system worked great so I pushed it out. Then I later accessed my blog from a mobile device and was surprised to see “undefined, undefined NaN NaN” where the date should have been.
Thankfully, my journey wasn’t terribly difficult. I was concurrently working on a project that used both App Engine and Angular, and happened to notice that App Engine’s date format worked in mobile browsers without any problems. App Engine’s format looks something like this:
2014-09-09T21:57:52.310916. You can get such a timestamp in Python with the following code:
from datetime import datetime def stop(s): print(s) hammer_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f') stop(hammer_time)
Terrible puns aside, it’s important to call
utcnow() instead of
now() so that time zone information is retained by normalizing to UTC.