Dates & Formatting in Javascript

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 two inputs:

RFC 2822
Sat Apr 12 2014 12:22:00 GMT+1000
Unix timestamp
1397269320000

But with ECMAScript 5 we can now also parse ISO 8601 dates, which gives us a little more leeway, but doesn't solve the problem of the Date object being unweildy to use.

ISO 8601
2014-04-12T12:22:00+10:00

To parse a date in plain Javascript, you can simply pass a well formed string to the constructor:

var dIso = new Date('2014-04-12T12:22:00+10:00'); // IE9+, no Safari.
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.

DateRaw JSMoment
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.