-
Get the week number with JavaScript
October 26th, 2007
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:<script type="text/javascript"> 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; } </script>Example – Get the week number of the current day:
<script type="text/javascript">
var mydate = new Date();
var weeknumber = mydate.getWeek();
</script>Example – Get the week number of 2 May 2008:
<script type="text/javascript">
var 2may2008 = new Date();
2may2008.setFullYear(2008, 4, 2);
var weeknumber = 2may2008.getWeek();
</script>
I tested the above method on IE 6+ and FF 2 and it works perfectly.
5 Responses to “Get the week number with JavaScript”
Hi.
I tried your script but I found a bug.
The 2009-12-31 return 53th week,
but 2010-01-01 return 01 week against 53th week.
The transition between 2 years must test the number of day of the first week.
If 2010-01-01 >= friday then first week begin the next monday.
Very useful function. Thank you.
Thanks, this function is very useful
VDE is correct, the last week of 2009 and first week of 2010 are technically the same week number (if im not mistaken, that would be week 53) And week 1 of 2010 should start on 3 Jan 2010
Thankyou very much needed this badly