/ Published in: JavaScript
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).
Usage:
var now = new Date;
console.log(now.toISOString());
Validates clean in JSLint (Edition 2012-12-31).
Usage:
var now = new Date;
console.log(now.toISOString());
Validates clean in JSLint (Edition 2012-12-31).
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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'; }; }()); }
URL: http://jsfiddle.net/davidwaterston/LMxwz/