1. Technology
Send to a Friend via Email

Day of Year

Adding to the Date Object

Join the Discussion

Questions? Comments?

Related Resources

Week of Year Julian Day

One of the simplest pieces of information about dates that the date object in Javascript doesn't provide is a way of determining which day of the year a particular date actually is (what is sometimes known as the Julian Date). We can easily add this method to the date function ourselves.

The code that we need to do this is actually very short so we'll start by looking at the code itself.

Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}

With the above code added to your Javascript, you now have the ability to call getDOY() on any date object that you define and retrieve the day number of that date within the current year.

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 today = new Date();
var daynum = today.getDOY();

We can of course get the day number for any date at all so if we want to know what day of the year that the 1st July is in 2007 (answer ) we can use the following code (remembering that the month in Javascript dates counts from 0 and not 1):

var jul07 = new Date(2007,6,1);
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.

See More About

©2014 About.com. All rights reserved.