Get the Day of the Year (1 - 366) using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 27, 2022

banner

Photo from Unsplash

Get the Day of the Year (1 - 366) using JavaScript #

To get the day of the year:

  1. Get a timestamp that represents the date.
  2. Get a timestamp that represents the last day of the previous year.
  3. Subtract the second timestamp from the first and convert the result to days.
index.js
function getDayOfYear(date = new Date()) { const timestamp1 = Date.UTC( date.getFullYear(), date.getMonth(), date.getDate(), ); const timestamp2 = Date.UTC(date.getFullYear(), 0, 0); const differenceInMilliseconds = timestamp1 - timestamp2; const differenceInDays = differenceInMilliseconds / 1000 / 60 / 60 / 24; return differenceInDays; } console.log(getDayOfYear(new Date('2022-02-01'))); // 👉️ 32 console.log(getDayOfYear(new Date('2022-01-29'))); // 👉️ 29 console.log(getDayOfYear(new Date('2022-03-01'))); // 👉️ 60 console.log(getDayOfYear(new Date('2022-12-31'))); // 👉️ 365

We created a reusable function that returns the number of the day of the year.

The function takes a Date object as a parameter or uses the current date if none is provided

The Date.UTC method takes similar parameters to the Date() constructor, but treats them as UTC and returns the number of milliseconds since the 1st of January 1970, 00:00:00 UTC.

We used the Date.UTC method to avoid any Daylight Saving Time (DST) issues.

In the first call to the method, we got a timestamp of the passed in date.

We used the following 3 date-related methods:

  • Date.getFullYear method - returns a four-digit number representing the year that corresponds to a date.

  • Date.getMonth - returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Yes, unfortunately the getMonth method is off by 1.

  • Date.getDate - returns an integer between 1 and 31 representing the day of the month for a specific date.

In our second call to the Date.UTC() method, we got a timestamp for the last day of the previous year.

We passed 0 for the month of January and 0 for the day.

Note that the value for the day of the month is not zero-based, it is one-based.

The Date object in JavaScript automatically takes care of rolling back or rolling over the values for the month and year, so we got a timestamp for the last day of the previous year.

Subtracting the second timestamp from the first, gives us the difference between the passed in date and the last day of the previous year in milliseconds.

The last step is to convert the difference from milliseconds to days to get the day of the year.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.