Day of Year

JavaScript provides Date methods for retrieving the day of the week and the day of the month but doesn't provide on for retrieving the day of the year. Adding our own method to retrieve this value is not all that difficult though. All we need to do is to compare two dates and return the answer in days.

When we set a date object without specifying a value for any of the time parameters, each of those values defaults to zero and the date is effectively set to midnight at the start of that day. We can make use of this to simplify our date comparison in determining the day of the year simply by rounding up any fractions of a day to the next whole day. One millisecond after midnight on 1st January will be rounded up to one so that our count of the day number starts from one for the first of January so that we will have values similar to the days of the month that start from one rather than like the days of the week which start from zero.

Our date comparison is then straightforward. Simply subtract midnight on 1st January from the current date/time and divide by the number of milliseconds in a day (since date objects are stored internally as a value in milliseconds) and then round the result up to the nearest integer value.

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


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow