Friday, July 23, 2010

Fun with Javascript Dates - II

1. Javascript Date object has many differences from .Net DateTime type. Some of the prominent differences are:
  • Month is zero based integer (0 to 11) - this can be a source of many a bug.
  • Weekday (getDay) returns 0-6 for Sunday-Saturday

    To get descriptive weekday, you can extend the date object's functionality like so:

    Date.prototype.getDayShort=function(){
    return ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][this.getDay()];
    }
    //Test it:
    alert((new Date(2010,1,1)).getDayShort())

    This will popup "Mon". Some of you are looking up the calendar and thinking "shouldn't 1st Jan be a Friday". No Siree, the date is 1st Feb -- did you already forget my month's tip above? I will leave it up to you to implement a getLongDay() function.

    The cool trick above is declare a lookup array on the fly. It saves a line of code, and an additional variable, and can be useful for small, one-time-use lookups. You can use the same trick with JSON objects. For example:

    alert({black:"#000000", blue:"0000ff", red:"#ff0000"}["blue"]);

    2. One biggie is the Y2K bug. Javascript and .Net have methods to create date objects from numbers. Javascript's Date(yy,mm,dd) constructor will treat all 2 digit year to be 19th century, while .Net has DateTime.Parse method which assumes years "0" to "29) to be 20th century. To mimic .Net's behavior check for date under 30, and add 2000, as shown below:

    for(var i=0;i<102;i++)
    console.log(new Date(i<30?i+2000:i,1,1));
  • No comments: