As of JavaScript 1.8, a new prototypal function for the Date objects has been added: toISOString(). Ordinarily this returns a string similar to the following:


2012-10-1T21:43:54.803Z

The problem is that not all browsers support JavaScript 1.8 yet. For this reason, if you want to use this function regardless of the version of JavaScript running, I suggest using the following conditional definition:


Date.prototype.toISOString = Date.prototype.toISOString || function() {
  return this.getUTCFullYear() + "-"
    + ("0" + (this.getUTCMonth() + 1) + "-").slice(-3)
    + ("0" + this.getUTCDate() + "T").slice(-3)
    + ("0" + this.getUTCHours() + ":").slice(-3)
    + ("0" + this.getUTCMinutes() + ":").slice(-3)
    + ("0" + this.getUTCSeconds() + ".").slice(-3)
    + ("00" + this.getUTCMilliseconds() + "Z").slice(-4);
};

The above code has been verified because it is based off of the alternative defined by MDN here. The reason mine is shorter is because, as you may already know, I love to incorporate shortcuts in my JavaScript in order to shorten code and lessen the amount of statements that have to run. On the other hand, if you think you can prove that my version is less efficient than the one suggested by the MDN, please leave a comment outlining how you came to this conclusion. Have fun!


2 Comments

Sean · February 9, 2013 at 12:32 PM

Had to make this change on line 3 to get it to work for me:

String(this.getUTCMonth() + 1)

Otherwise, works like a charm. Thanks šŸ™‚

    Chris West · February 10, 2013 at 4:40 AM

    Wow, I can’t believe I overlooked that. I corrected it in the post. Thanks! 8)

Leave a Reply to Chris West Cancel reply

Your email address will not be published. Required fields are marked *