11

Possible Duplicate:
How do I output an ISO-8601 formatted string in Javascript?

I have a date like

Thu Jul 12 2012 01:20:46 GMT+0530

How can I convert it into ISO-8601 format like this

2012-07-12T01:20:46Z
Community
  • 1
  • 1
Bhoot
  • 390
  • 1
  • 3
  • 13

2 Answers2

28

In most newer browsers you have .toISOString() method, but in IE8 or older you can use the following (taken from json2.js by Douglas Crockford):

// Override only if native toISOString is not defined
if (!Date.prototype.toISOString) {
    // Here we rely on JSON serialization for dates because it matches 
    // the ISO standard. However, we check if JSON serializer is present 
    // on a page and define our own .toJSON method only if necessary
    if (!Date.prototype.toJSON) {
        Date.prototype.toJSON = function (key) {
            function f(n) {
                // Format integers to have at least two digits.
                return n < 10 ? '0' + n : n;
            }

            return this.getUTCFullYear()   + '-' +
                f(this.getUTCMonth() + 1) + '-' +
                f(this.getUTCDate())      + 'T' +
                f(this.getUTCHours())     + ':' +
                f(this.getUTCMinutes())   + ':' +
                f(this.getUTCSeconds())   + 'Z';
        };
    }

    Date.prototype.toISOString = Date.prototype.toJSON;
}

Now you can safely call `.toISOString() method.

6

There's the .toISOString() method on date. You can use that for Browsers with support for ECMA-Script 5. For those without, install the method like this:

if (!Date.prototype.toISOString) {
    Date.prototype.toISOString = function() {
        function pad(n) { return n < 10 ? '0' + n : n };
        return this.getUTCFullYear() + '-'
            + pad(this.getUTCMonth() + 1) + '-'
            + pad(this.getUTCDate()) + 'T'
            + pad(this.getUTCHours()) + ':'
            + pad(this.getUTCMinutes()) + ':'
            + pad(this.getUTCSeconds()) + 'Z';
    };
}
LoveGandhi
  • 402
  • 4
  • 13
Beat Richartz
  • 9,474
  • 1
  • 33
  • 50