Convert Day of Year to Date using JavaScript


Borislav Hadzhiev

Last updated: Jan 28, 2022


Photo from Unsplash

Convert Day of Year to Date using JavaScript #

To convert the day of the year to a date:

  1. Use the Date() constructor to create a new Date object.
  2. Pass the year, 0 for the month and the day of the year to the constructor.
  3. The Date() constructor will convert the day of the year to a date.
function dayToDate(year, day) { const date = new Date(year, 0, day); return date; } // 👇️ Sat Jan 15 2022 console.log(dayToDate(2022, 15)); // 👇️ Mon Feb 14 2022 console.log(dayToDate(2022, 45)); // 👇️ Tue Mar 01 2022 console.log(dayToDate(2022, 60));

We created a reusable function that takes the year and day of the year as parameters and returns a Date object.

The 3 parameters we passed to the Date() constructor are:

  1. the year
  2. a zero-based value for the month, where January is 0, February is 1, March is 2, etc.
  3. the day
We used 0 for the month when calling the Date constructor to set the month of the date to January and directly passed the day of the year for the day.

The Date object in JavaScript automatically rolls over the months or years depending on the passed in value.

// 👇️ Tue Feb 01 2022 console.log(new Date(2022, 0, 32));

We created a date in January and used 32 as the day of the month parameter.

The Date object knows that there are only 31 days in January, so it set the month to February.

The dayToDate function expects a number from 1 to 365 or 366 (leap year) for the day of the year parameter.

If you pass a greater value, the year will get adjusted as well.

// 👇️ Sun Jan 01 2023 console.log(new Date(2022, 0, 366));

Because 2022 is not a leap year, passing 366 as the day of the month parameter to the Date() constructor pushes us into the next 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.