-
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.