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

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

    You have a few options;

    If you're using a standard format, you can do something like:

    new Date(dateStr);
    

    If you'd rather be safe about it, you could do:

    var date, timestamp;
    try {
        timestamp = Date.parse(dateStr);
    } catch(e) {}
    if(timestamp)
        date = new Date(timestamp);
    
    or simply,    
    
    new Date(Date.parse(dateStr));
    

    Or, if you have an arbitrary format, split the string/parse it into units, and do:

    new Date(year, month - 1, day)
    

    Example of the last:

    var dateStr = '28/10/2010'; // uncommon US short date
    var dateArr = dateStr.split('/');
    var dateObj = new Date(dateArr[2], parseInt(dateArr[1]) - 1, dateArr[0]);
    

提交回复
热议问题