i have to transform a number (0-364) to date starting from January 01, 2013. Example: 00 = Jan 01, 2013 or 45 = 15 Feb, 2013; 364= 31 Dec, 2013
Asked
Active
Viewed 203 times
0
-
Don't forget the leap year cases. – Bathsheba Jul 04 '13 at 11:28
3 Answers
4
If you construct a new Date
, but specify a day
value that is too large, the day value will 'overflow' and increment the months. As such, you can do the following:
days = 1;
date = new Date(2013, 0, days);
// => Tue Jan 01 2013 00:00:00 GMT+1100 (EST)
days = 46;
date = new Date(2013, 0, days);
// => Fri Feb 15 2013 00:00:00 GMT+1100 (EST)
days = 365;
date = new Date(2013, 0, days);
// => Tue Dec 31 2013 00:00:00 GMT+1100 (EST)
Note that using this method, days
starts from 1 for the start of the year. If you want days == 0
to produce 01 Jan, 2013
, you will need to use: new Date(2013, 00, days + 1);

Tim Heap
- 1,671
- 12
- 11
-
-
1Perfect solution imo, just one note: the requested year was *2013*, but it doesn't matter a lot, moreover you should do `days + 1` or providing `0` as days will return in 31st of December of the previous year :) – Niccolò Campolungo Jul 04 '13 at 11:33
-
@LightStyle Good point, I updated my example to reflect 0 meaning 01-Jan – Tim Heap Jul 04 '13 at 11:35
-
1
Try something like this :
// initialize to start of the year
var dt= new Date(2013,00,01);
// add the required number of days to date
dt.setDate(dt.getDate() + <number of days>);
where <number of days>
is your variable

Manse
- 37,765
- 10
- 83
- 108
-
-
@AlinaFloreaHodoroaba then look at the documentation and work out for your self how to present the date how you require -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Manse Jul 04 '13 at 14:40
0
You can use the getTime():
var days = xxx;
var date = new Date(2013, 0, 1);
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
console.log( new Date(res) );

Sharon
- 88
- 6