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

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

提交回复
热议问题