3

I'm using js and jquery. I've been looking on the page and I found this: Javascript calculate the day of the year (1 - 366) I'm trying to do the oposite.

For example:

208 would be today (2016/07/26)

Any idea how could i do this?

Thank you very much in advance.

Community
  • 1
  • 1
Hector Landete
  • 357
  • 1
  • 6
  • 15

4 Answers4

8

Try this:

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
}

dateFromDay(2016, 208); 
Jayesh Chitroda
  • 4,987
  • 13
  • 18
6

The shortest way:

new Date(2016, 0, 208)

will return Date 2016-07-26

Yan Pak
  • 1,767
  • 2
  • 19
  • 15
-1

function dayNumToDate(numDays) {
  var thisYear = new Date().getFullYear();
  var initDate = new Date("JANUARY, 1," +  thisYear);
  var millis = numDays * 24 * 60 *60 * 10000; 
  var newDate = new Date(millis + initDate.getTime());
  return newDate;
}
var date = dayNumToDate(208);
alert(date.toString());
Jordi Flores
  • 2,080
  • 10
  • 16
-1

//To initialize date function

var now = new Date();

// the number of day to convert in Date

var curr_day_number = 208;

//Calculate total time of a single day

var oneDay = 1000 * 60 * 60 * 24;

//Calculate total time all days so

var total_number_of_time_of_day = curr_day_number * oneDay;

//calcuclate start day of the year

var start_date_of_year = new Date(now.getFullYear(), 0, 0);

//calculate start date of year time stamp

var start_date_of_year_timestamp = new Date(start_date_of_year).getTime();

//calulate total time stamp start of the year with total days of the year

var calculated_timestamp = start_date_of_year_timestamp + total_number_of_time_of_day; 

// convert time stamp into Date using Date function

var calculated_date = new Date(calculated_timestamp);

document.write(calculated_date);

This will help you out in detail.

  • There is solution with only one line. It complies with the specification, is concise and easily readable. So why would anyone want to use a solution that spans several lines, makes potentially error-prone calculations, and is hard to read and understand? – str Jul 26 '16 at 12:50