Dates and Javascript haven't traditionally been very nice. The
Date object
is the only real API for managing dates and code to deal with it can be extremely verbose.
Parsing dates with Javascript
Parsing dates has traditionally been difficult with the Date object only supporting non-standardised inputs dependent on the browser:
- RFC 2822
- Sat Apr 12 2014 12:22:00 GMT+1000
- Unix timestamp
- 1397269320000
But with ECMAScript 5 we can also parse ISO 8601 dates, which gives us a little more leeway. From the MDN date docs:
simplified extended ISO format (ISO 8601) is always 24 or 27 characters long
(YYYY-MM-DDTHH:mm:ss.sssZ
or±YYYYYY-MM-DDTHH:mm:ss.sssZ
, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".
To parse a date in plain Javascript, you can now pass a well formed ISO8601 string to the constructor:
var dIso = new Date('2014-04-12T12:22:00.000+10:00');
var dRfc = new Date('Sat Apr 12 2014 12:22:00 GMT+1000');
var dUnix = new Date(1397269320000);
All the above will all return a valid date. Note that the Unix timestamp is in milliseconds. If you're trying to read a Unix timestamp in seconds you may need to multiply it by 1000.
Update: Turns out Safari is a laggard with ISO 8601 dates and like IE8, can't parse them at all. If you need ISO8601 dates on the client, you'll have to resort to either a custom solution or something like moment.js which supports parsing them.
Formatting dates in Javascript
The problem of formatting dates in a particular way in Javascript is difficult. If you wanted to print a basic YYYY-MM-DD
timestamp you could do something like the following, but you'd also have to implement logic around padding zeroes and incrementing the zero-based month and the syntax for the most basic notation is horrible. It's no fun.
var d = new Date();
return d.getYear() + '-' + (d.getMonth+1) + '-' + d.getDay();
// 2014-4-12
One of the better libraries for managing dates in Javascript is Moment.js, which brings slick chainable date handling to the browser (or node). The main downfall is that it’s quite heavy, but when you need to be able to manipulate a lot of dates it’s totally worth it.
Our previous example can be condensed into the following:
return moment().format('YYYY-MM-DD');
Moment has some other sweet features, particularly around date parsing and manipulation so you should definitely check it out.
Specific date formats in JS and Moment
While we're at it, here's a cheat sheet of specific date formats you may need to use in JS.
Date | Raw JS | Moment |
---|---|---|
RFC 2822 | myDate.toUTCString() |
moment().format('ddd, DD MMM YYYY HH:mm:ss ZZ') |
ISO 8601 | myDate.toISOString() * |
moment().toISOString() |
Unix Timestamp | Number(myDate) |
moment().valueOf() |
Note that the native Date.toISOString
method was introduced in ECMAScript 5, so only works in IE 9 and above.