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

"I want to take a day of the year and convert to an actual date using the Date object."

After re-reading your question, it sounds like you have a year number, and an arbitrary day number (e.g. a number within 0..365 (or 366 for a leap year)), and you want to get a date from that.

For example:

dateFromDay(2010, 301); // "Thu Oct 28 2010", today ;)
dateFromDay(2010, 365); // "Fri Dec 31 2010"

If it's that, can be done easily:

function dateFromDay(year, day){
  var date = new Date(year, 0); // initialize a date in `year-01-01`
  return new Date(date.setDate(day)); // add the number of days
}

You could add also some validation, to ensure that the day number is withing the range of days in the year supplied.


// You might need both parts of it-

Date.fromDayofYear= function(n, y){
    if(!y) y= new Date().getFullYear();
    var d= new Date(y, 0, 1);
    return new Date(d.setMonth(0, n));
}
Date.prototype.dayofYear= function(){
    var d= new Date(this.getFullYear(), 0, 0);
    return Math.floor((this-d)/8.64e+7);
}

var d=new Date().dayofYear();
//
alert('day#'+d+' is '+Date.fromDayofYear(d).toLocaleDateString())


/*  returned value: (String)
day#301 is Thursday, October 28, 2010
*/

The shortest possible way is to create a new date object with the given year, January as month and your day of the year as date:

const date = new Date(2017, 0, 365);

console.log(date.toLocaleDateString());

As for setDate the correct month gets calculated if the given date is larger than the month's length.