Hector Landete
Hector Landete

Reputation: 367

Get full date from day of the year

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.

Upvotes: 3

Views: 544

Answers (4)

Zaik Chohan
Zaik Chohan

Reputation: 69

//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.

Upvotes: -1

Jordi Flores
Jordi Flores

Reputation: 2150

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());

Upvotes: -1

Yan Pak
Yan Pak

Reputation: 1867

The shortest way:

new Date(2016, 0, 208)

will return Date 2016-07-26

Upvotes: 6

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

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); 

Upvotes: 8

Related Questions