Return to Snippet

Revision: 61763
at January 14, 2013 04:58 by davidwaterston


Updated Code
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';
        };

    }());
}

Revision: 61762
at January 14, 2013 04:56 by davidwaterston


Initial Code
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';
        };

    }());
}

Initial URL
http://jsfiddle.net/davidwaterston/LMxwz/

Initial Description
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).

Initial Title
Convert a Date object to an ISO 8601 formatted string

Initial Tags
javascript, date

Initial Language
JavaScript