Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a normal date to ISO-8601 format [duplicate]

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
like image 513
Bhoot Avatar asked Jul 11 '12 20:07

Bhoot


People also ask

Is ISO 8601 always UTC?

The toISOString() method returns a string in ISO format (ISO 8601 Extended Format), which can be described as follows: YYYY-MM-DDTHH:mm:ss. sssZ . The timezone is always UTC as denoted by the suffix "Z".

What is Z in ISO 8601 date format?

Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "T0930Z". "14:45:15 UTC" would be "14:45:15Z" or "T144515Z". The Z suffix in the ISO 8601 time representation is sometimes referred to as "Zulu time" because the same letter is used to designate the Zulu time zone.

How do I convert datetime to ISO 8601 in Python?

To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'.


1 Answers

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.

like image 59