John Russell Blog

Using JavaScript to Determine the Number of Days Between the Beginning of the Year and a Given Date

I recently came across the need to determine how many days fell between the beginning of the year and a given date. The most convenient way to do this is to add a new method to the Date object. Let’s get started!

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

Looking at the above code, line one allows us to add a new method to the Date object by adding a new function to its prototype. This will allow the getDOY method to be invoked on any Date object, such as myDateObject.getDOY(). The getDOY function name stands for “get day of year” and will return the day of year between 1 and 365. The way this works is by first creating a new Date object with the current year, January for the month, and 1 for the day. Next, the Date object (referenced by the keyword this) is equal to the amount of milliseconds since January 1, 1970 to present time, and subtracting the amount of milliseconds from January 1, 1970 to January 1 of the current year will leave you with the amount of milliseconds from the beginning of the year to the current date and time. The only thing left to be done is to convert the milliseconds to days, which can be done by dividing the number by 86,400,000 (1000 milliseconds  x  60 seconds  x  60 minutes  x  24 hours).

There you have it!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *