how can I convert day of year to date in javascript?

后端 未结 9 1039
一整个雨季
一整个雨季 2020-11-30 08:48

I want to take a day of the year and convert to an actual date using the Date object. Example: day 257 of 1929, how can I go about doing this?

9条回答
  •  失恋的感觉
    2020-11-30 09:33

    If you always want a UTC date:

    function getDateFromDayOfYear (year, day) {
      return new Date(Date.UTC(year, 0, day))
    }
    
    console.log(getDateFromDayOfYear(2020, 1)) // 2020-01-01T00:00:00.000Z
    console.log(getDateFromDayOfYear(2020, 305)) // 2020-10-31T00:00:00.000Z
    console.log(getDateFromDayOfYear(2020, 366)) // 2020-12-31T00:00:00.000Z

提交回复
热议问题