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

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

    0 讨论(0)
  • 2020-11-30 09:34

    Here is a function that takes a day number, and returns the date object

    optionally, it takes a year in YYYY format for parameter 2. If you leave it off, it will default to current year.

    var getDateFromDayNum = function(dayNum, year){
    
        var date = new Date();
        if(year){
            date.setFullYear(year);
        }
        date.setMonth(0);
        date.setDate(0);
        var timeOfFirst = date.getTime(); // this is the time in milliseconds of 1/1/YYYY
        var dayMilli = 1000 * 60 * 60 * 24;
        var dayNumMilli = dayNum * dayMilli;
        date.setTime(timeOfFirst + dayNumMilli);
        return date;
    }
    

    OUTPUT

    // OUTPUT OF DAY 232 of year 1995
    
    var pastDate = getDateFromDayNum(232,1995)
    console.log("PAST DATE: " , pastDate);
    

    PAST DATE: Sun Aug 20 1995 09:47:18 GMT-0400 (EDT)

    0 讨论(0)
  • 2020-11-30 09:37

    If I understand your question correctly, you can do that from the Date constructor like this

    new Date(year, month, day, hours, minutes, seconds, milliseconds)
    

    All arguments as integers

    0 讨论(0)
提交回复
热议问题