Javascript - weak on getting week

by DotNetNerd 23. December 2009 08:42

Well this is one of those posts that start out being as a reminder for myself, since I had to do a script that I don't want to waste my time having to write again later on. Basically I ran into a customer who wanted week numbers added to a calendar. This seemed basic enough, but apparently getting a weeknumber is not a native thing in javascript.

First I picked up a script to add a getWeek method to the Date prototype, and I was a happy man. Sadly not customer not quite as much. It turns out that we do not follow the ISO 8601 standard for defining weeknumbers here in Denmark. According to my projectmanager the rule of thumb is that the first thursday always falls in week 1. This made me add a little extention so I now have a getIsoWeek and a getWeek method on my Date objects and this is how it was done.

/**
* Get the ISO 8601 week date week number
*/
Date.prototype.getIsoWeek = function() {
    // Create a copy of this date object 
    var target = new Date(this.valueOf());

    // ISO week date weeks start on monday 
    // so correct the day number 
    var dayNr = (this.getDay() + 6) % 7;

    // Set the target to the thursday of this week so the 
    // target date is in the right year 
    target.setDate(target.getDate() - dayNr + 3);

    // ISO 8601 states that week 1 is the week 
    // with january 4th in it 
    var jan4 = new Date(target.getFullYear(), 0, 4);

    // Number of days between target date and january 4th 
    var dayDiff = (target - jan4) / 86400000;

    // Calculate week number: Week 1 (january 4th) plus the  
    // number of weeks between target date and january 4th  
    var weekNr = 1 + Math.ceil(dayDiff / 7);

    return weekNr;
}

/**
* Get danish weeknumber.
* According to danish weeknumbers the first thursday always falls in week 1
*/
Date.prototype.getWeek = function() {
    var weekNr = this.getIsoWeek();

    var firstThursday = new Date(this.getFullYear(), 0, 1)
    while (firstThursday.getDay() != 4) firstThursday.setDate(firstThursday.getDate() + 1);

    if (firstThursday.getIsoWeek() == 2) weekNr--;

    if (weekNr == 0) weekNr = 1;

    return weekNr;
}

Tags:

Who am I?

My name is Christian Holm Diget, and I work as an independent consultant, in Denmark, where I write code, give advice on architecture and help with training. On the side I get to do a bit of speaking and help with miscellaneous community events.

Some of my primary focus areas are code quality, programming languages and using new technologies to provide value.

Microsoft Certified Professional Developer

Microsoft Most Valuable Professional

Month List

bedava tv izle