How do I output an ISO 8601 formatted string in JavaScript?
There is already a function called toISOString()
:
var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"
If, somehow, you're on a browser that doesn't support it, I've got you covered:
if (!Date.prototype.toISOString) {
(function() {
function pad(number) {
var r = String(number);
if (r.length === 1) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) +
'Z';
};
}());
}
console.log(new Date().toISOString())
Note: This answer is still getting upvotes as of 2022-03. The moment.js library is deprecated. These are the two main alternatives: Luxon and Day.js, others are mentioned in the deprecation link.
Luxon
Luxon can be thought of as the evolution of Moment. It is authored by Isaac Cambron, a long-time contributor to Moment. Please read Why does Luxon exist? and the For Moment users pages in the Luxon documentation.
Locales: Intl provided Time Zones: Intl provided
Day.js
Day.js is designed to be a minimalist replacement for Moment.js, using a similar API. It is not a drop-in replacement, but if you are used to using Moment's API and want to get moving quickly, consider using Day.js.
Locales: Custom data files that can be individually imported Time Zones: Intl provided, via a plugin
I use Day.js because of the size difference, but Luxon is easier to deal with.
Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.
This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.
The best solution I've come across is to use the Moment.js javascript library and use the following code:
To get the current ISO time with timezone information and milliseconds
now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T20:11:11.234+0100"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T19:11:11.234+0000"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
// "2013-03-08T19:11:11Z" <- better use the native .toISOString()
To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds
var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.
A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.