How to convert day of year to a date in JavaScript?

Sometimes, we want to convert day of year to a date in JavaScript.

In this article, we’ll look at how to convert day of year to a date in JavaScript.

How to convert day of year to a date in JavaScript?

To convert day of year to a date in JavaScript, we can call the Date constructor with the year and 9 for the rest of the arguments.

For instance, we write:

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

We create the dateFromDay function with the year and day parameters.

In the function, we instantiate the Date instance with year and 0 for month.

Then we call date.setDate with day which is set to 1 by default.

As a result, we see Sat Jan 01 2022 00:00:00 GMT-0800 (Pacific Standard Time) logged.

Conclusion

To convert day of year to a date in JavaScript, we can call the Date constructor with the year and 9 for the rest of the arguments.