Categories
JavaScript Answers

How to Convert the Day of the Year to a Date Object in JavaScript?

Spread the love

To convert the day of the year to a date object in JavaScript, we can pass the year into the Date constructor.

For instance, we can write:

const dateFromDay = (year, day) => {
  const date = new Date(year, 0);
  return new Date(date.setDate(day));
}

console.log(dateFromDay(2020, 301))

to create the dateFromDay function that takes the year and day parameters.

We pass the year into the Date constructor when we create the date object.

Then we call setDate with day to set the day of the year.

Therefore, the console log should log:

Tue Oct 27 2020 00:00:00 GMT-0700 (Pacific Daylight Time)

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.