CHunky Universe of Vigourous 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:


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

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: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

Daniel Chronlund Cloud Tech Blog

News, tips and thoughts for Microsoft cloud fans

Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager - Architect, Speaker, Author

Microsoft 365, SharePoint and Azure

SharePoint Dragons

Nikander & Margriet on SharePoint

Mai Omar Desouki

PFE @ Microsoft

Cameron Dwyer

Office 365, SharePoint, Azure, OnePlace Solutions & Life's Other Little Wonders


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

Aryan Nava

DevOps, Cloud and Blockchain Consultant


SharePoint for everyone


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

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint


Mostly what I know and share about...

%d bloggers like this: