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

后端 未结 9 1053
一整个雨季
一整个雨季 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:11

    Here's my implementation, which supports fractional days. The concept is simple: get the unix timestamp of midnight on the first day of the year, then multiply the desired day by the number of milliseconds in a day.

    /**
     * Converts day of the year to a unix timestamp
     * @param {Number} dayOfYear 1-365, with support for floats
     * @param {Number} year (optional) 2 or 4 digit year representation. Defaults to
     * current year.
     * @return {Number} Unix timestamp (ms precision)
     */
    function dayOfYearToTimestamp(dayOfYear, year) {
      year = year || (new Date()).getFullYear();
      var dayMS = 1000 * 60 * 60 * 24;
    
      // Note the Z, forcing this to UTC time.  Without this it would be a local time, which would have to be further adjusted to account for timezone.
      var yearStart = new Date('1/1/' + year + ' 0:0:0 Z');
    
      return yearStart + ((dayOfYear - 1) * dayMS);
    }
    
    // usage
    
    // 2015-01-01T00:00:00.000Z
    console.log(new Date(dayOfYearToTimestamp(1, 2015)));
    
    // support for fractional day (for satellite TLE propagation, etc)
    // 2015-06-29T12:19:03.437Z
    console.log(new Date(dayOfYearToTimestamp(180.51323423, 2015)).toISOString);
    

提交回复
热议问题