Skip to content

Instantly share code, notes, and snippets.

@davidwaterston
Created January 13, 2013 09:16
Show Gist options
  • Save davidwaterston/4523142 to your computer and use it in GitHub Desktop.
Save davidwaterston/4523142 to your computer and use it in GitHub Desktop.
Javascript: converts a Date object into an ISO 8601 formatted string.
if (typeof Date.prototype.toISOString !== 'function') {
(function () {
'use strict';
// Function which takes a 1 or 2-digit number and returns it as a two-character string,
// padded with an extra leading zero, if necessary.
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';
};
}());
}
@davidwaterston
Copy link
Author

Javascript which converts a Date object into an ISO 8601 formatted string - 'YYYY-MM-DDTHH:mm:ss.sssZ' - with a fallback for when the function 'toISOString' doesn't exist (e.g. IE 8 or less).
jsFiddle: http://jsfiddle.net/davidwaterston/LMxwz/

Usage:
var now = new Date;
console.log(now.toISOString());

Validates clean in JSLint (Edition 2012-12-31).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment