Get the week number with JavaScript

Update: I have found a better way to get the week number with JavaScript here.

A few days ago I needed to code a little calendar in JavaScript. While I was doing this, I needed a piece of code to get the week number of a date.

If you, for example, need to get the day of the month with JavaScript you can use this:

var mydate = new Date();
month = mydate.getMonth();
									


I wanted to get a ISO 8601 week number with the same method. You can use this piece of code to get this actually working:

Date.prototype.getWeek = function() {
    var determinedate = new Date();
    determinedate.setFullYear(this.getFullYear(), this.getMonth(), this.getDate());
    var D = determinedate.getDay();
    if(D == 0) D = 7;
    determinedate.setDate(determinedate.getDate() + (4 - D));
    var YN = determinedate.getFullYear();
    var ZBDoCY = Math.floor((determinedate.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
    var WN = 1 + Math.floor(ZBDoCY / 7);
    return WN;
}
									


[ad#hoofdbanner]
Example – Get the week number of the current day:

var mydate = new Date();
var weeknumber = mydate.getWeek();
									


Example – Get the week number of 2 May 2008:

var 2may2008 = new Date();
2may2008.setFullYear(2008, 4, 2);
var weeknumber = 2may2008.getWeek();

									


I tested the above method on IE 6+ and FF 2 and it works perfectly.

This entry was posted in Tech. Bookmark the permalink.

13 Responses to Get the week number with JavaScript

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.