EcmaScript 5's Date Extensions

by tracker1 7. January 2010 10:44

Okay, so you want to utilize some of the niceties of the new EcmaScript 5 extensions to Date.  Namely they've added a nice instantiation from an ISO-8601-style string, as well as a Date.prototype.toISOString method definition.  In addition there are Date.UTC and Date.now methods defined.  As the nice guys over at Mozilla have offered script based extensions to Arrays to support their method extensions there, I wanted to do something similar for Date instances.  I've managed to do this, and have had it done since the ES5 specs were released, but figured I should put this out there for anyone interested.

var epoch1 = new Date("1970-01-01T00:00:00.000Z");
var epoch2 = new Date(0);

if (epoch1.getTime() == epoch2.getTime())
    alert("Epochs match!");
    
alert(epoch1.toString()); //localized date instance of the JS epoch
alert(epoch2.toISOString()); // "1970-01-01T00:00:00.000Z"
alert(epoch1 instanceof Date); // true
alert(epoch1.constructor == Date); //true
alert(Date.UTC(1970,0,1,0,0,0,0)); // 0

I also have a few convenience methods for handling Microsoft's JSON encoded strings. As well as rolling a date from a "Local" or "UTC" version.

DateExtensions.js (11.67 kb)

Edit 2010-01-08: I added missing support for .constructor == Date

Tags: , ,

JavaScript

Comments are closed

Powered by BlogEngine.NET 1.5.0.7

About Tracker1

Michael J. Ryan aka Tracker1

My name is Michael J. Ryan aka tracker1 (or azTracker1) and I've been developing web based solutions since the mid 90s.  My contact information and resume are online at tracker1.info.

Books

Ads