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)