is the only real API for managing dates and code to deal with it can be extremely verbose.
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
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
±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".
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.
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
Our previous example can be condensed into the following:
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.
Note that the native
Date.toISOString method was introduced in ECMAScript 5, so only works in IE 9 and above.