1

From this question I get a very useful function, which can calculate the day of the year from a date.

My question is that how can I reverse it?

So when I pass a number to the function's parameter, which is the day of the year, the function returns a date?

Here's the code:

var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
console.log('Day of year: ' + day);
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64

3 Answers3

2

Here is a function if you pass the year and the nth day of that year this will return the date of that nth day.

function dateFromDay(year, day){
  var date = new Date(year, 0); 
  return new Date(date.setDate(day));
}
console.log(dateFromDay(2010, 301));
console.log(dateFromDay(2010, 365));
Harish Soni
  • 1,796
  • 12
  • 27
  • Remarkable, identical code to [*this answer*](https://stackoverflow.com/questions/4048688/how-can-i-convert-day-of-year-to-date-in-javascript/4049020#4049020) from 2010. Even the examples are identical. If you find a duplicate, mark the question as a duplicate. If you copy someone else's code, give attribution and a link. – RobG May 30 '18 at 05:04
1

I think that this question should answer your problem. Simply instantiate a new Date at the beginning of the year - January 1st - and add the number of days to get to the x-th one.

Hope it helps.

Adrien B
  • 13
  • 4
1

Add this after your code. There is the working fiddle https://jsfiddle.net/andreitodorut/ubLxy174/

var yearBegining = new Date();
    yearBegining.setMonth(0,0);

    yearBegining.setTime((yearBegining.getTime()/1000 + (86000 * day)) * 1000);

You can check the results with this content https://www.epochconverter.com/days/2018

Andrei Todorut
  • 4,260
  • 2
  • 17
  • 28
  • Not all days are 24 hours long where daylight saving is observed, so you can't treat them as if they are. In the OP, the use of *Math.floor* removes the daylight saving effect when calculating the day number. Algorithms such as the one used in the duplicate do a similar thing using *setDate* rather than using the time value directly. – RobG May 30 '18 at 05:06