Day of Year
Adding to the Date Object
The code that we need to do this is actually very short so we'll start by looking at the code itself.
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
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 day 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 we have our answer. Note that the way that we are doing this means that we don't need to concern ourselves at all with the number of days in each month and whether the current year is a leap year or not the way that most day of year functions do as the method that we are using to determine our answer doesn't need to know any of that in order to work.
So let's take a quick look at how to use it. The current day number for today is . We can obtain that value by using the following code.
var daynum = today.getDOY();
var daynum = jul07.getDOY();
Of course the answer returned for any date in January or February will always be the same while those for March through December will have only two possible values depending on whether it is a leap year or not. The processing is therefore a lot more useful in situations such as our first example where the date is being dynamically set rather than as in our second example where the answer fixed.