Week of Year
Adding to the Date Object
The first thing we need to do is to work out how we define when a week starts and finishes and how we determine which week a particular date is in. The getDay() method returns a value of 0 for Sunday and 6 for Saturday so let's start by defining our week as running from Sunday to Saturday. The 1st January can fall on any day of the week and so not all of the days in that week will be in the current year but we'll consider the week that contains the 1st January to be week one of the current year even though not all of the days in that week are necessarily in the current year. So week one consists of those days between 1st January and the first Saturday on or after that date and the seven days following that make up week two and so on. Once we get to the end of December the last few days of the year will be in week 53 (or possibly 54 if it is a leap year starting on a Saturday).
Actually it sounds a lot more complicated than it is and it certainly took me a lot longer to write the description of how this method should work than it did to write the method itself.
The code to do all this is actually fairly short.
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
So how does this short piece of code work out what week it is? Well all of the dates are stored internally as the number of milliseconds from midnight on 1st January 1970. By subtracting that internal value for 1st January of the desired year from the date we want the week number for we get the number of milliseconds to that date from the start of that year. Dividing by 86400000 converts that into the number of days from the start of the year and adding the day of the week that the 1st January falls on gives us the number of days since the Sunday of what we want to use as week one. Since there are seven days in a week all that remains is to divide that number of days by seven and round it up to the next whole number in order to give us the week number we are after.
So let's take a quick look at how to use it. The current week number for today is . We can obtain that value by using the following code.
var weekno = today.getWeek();
var weekno = jul07.getWeek();