CHUVASH.eu

CHunky Universe of Vigouros Astonishing SHarepoint :)

format javascript date in ISO 8601

There is a solution in StackOverflow:

/* use a function for the exact format desired... */
function ISODateString(d){
 function pad(n){return n<10 ? '0'+n : n}
 return d.getUTCFullYear()+'-'
      + pad(d.getUTCMonth()+1)+'-'
      + pad(d.getUTCDate())+'T'
      + pad(d.getUTCHours())+':'
      + pad(d.getUTCMinutes())+':'
      + pad(d.getUTCSeconds())+'Z'}

var d = new Date();
print(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

But there is already a function for this: toISOString, it came with ecmascript 5. Unfortunately, not all browsers support this, to solve this problem, we can provide our own prototype function for Date if it doesn’t exist:

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

By the way, if you want to create an ISO string of DateTime in C#, use ToString(“s”):

var today = DateTime.Today;
var monthAgo = today.AddDays(-30);
var t = monthAgo.ToString("s");

Another way to convert a javascript date to ISO is to use JSON.stringify. The difference is that you get the date in ISO format surrounded with quotation marks. The curious thing is that Sys.Serialization.JavaScriptSerializer.serialize should do the same, but it returns the date in different format:

So it is the same date. Actually there is a deserialize function, too:

Sys.Serialization.JavaScriptSerializer.deserialize

But why does the date look like “”\/Date(1326234740861)\/””. But when we get objects from an ajax call, we just get: “/Date(1326234740861)/”. The explanation must be in the deserialization inside $.ajax.

Parse Dates From ISO 8601

What if you want to create a date from iso in javascript. It is no problem if you use modern browsers:

var date = new Date(isoString);

But not in IE. Here it fails. So we have to create custom parsing functions for that. D-oh. (One solution could be to use moment.js):

Date.fromISOString = function (iso) {
    ///<summary>Is used to parse iso 8601 dates in IE
    ///partly inspired from https://github.com/csnover/js-iso8601/blob/master/iso8601.js
    ///and http://n8v.enteuxis.org/2010/12/parsing-iso-8601-dates-in-javascript/
    ///</summary>
    var date = new Date(iso);
    if (isNaN(date)) {
        var minutesOffset = 0, numericKeys = [1, 4, 5, 6, 7, 10, 11];
        var struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/ .exec(iso);
        // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
        for (var i = 0, k; (k = numericKeys[i]); ++i) {
            struct[k] = +struct[k] || 0;
        }

        // allow undefined days and months
        struct[2] = (+struct[2] || 1) - 1;
        struct[3] = +struct[3] || 1;

        if (struct[8] !== 'Z' && struct[9] !== undefined) {
            minutesOffset = struct[10] * 60 + struct[11];

            if (struct[9] === '+') {
                minutesOffset = 0 - minutesOffset;
            }
        }
        var s = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
        date = new Date(s);
    }
    return date;
};
About these ads

2 responses to “format javascript date in ISO 8601

  1. joarobles 2012-12-27 at 14:45

    excellent! i was looking for this functionality for the Date() object and finally used the ISODateString() you provide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Discovering SharePoint

And having fun doing it

Bram de Jager's SharePoint blog

My view and thoughts on SharePoint.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

The Zuul Cat Idea Brewery

Where ideas on software development and entrepreneurship brew.

Paul J. Swider

Inspire! Teach! Awe!

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Alexander Ahrens

MCPD | SharePoint | Web Development | JavaScript | .NET

Cameron Dwyer | SharePoint, Outlook, OnePlaceMail

OnePlaceMail, SharePoint, Outlook & Life's Other Little Wonders

.:paul.tavares:.

Me and My doings!

Share SharePoint Points

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan.com

Ryan Dennis is a SharePoint Solutions Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

Follow

Get every new post delivered to your Inbox.

Join 186 other followers

%d bloggers like this: