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.

Leave a Comment