Created
January 13, 2013 09:16
-
-
Save davidwaterston/4523142 to your computer and use it in GitHub Desktop.
Javascript: converts a Date object into an ISO 8601 formatted string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
}; | |
}()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).