Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Example: day 257 of 1929, how can I go about doing this?

like image 366
Mike Croteau Avatar asked Oct 29 '10 03:10

Mike Croteau


People also ask

How do you find the date from the day of the year?

To get a real date from day number, or "nth day of year" you can use the DATE function. The DATE function build dates from separate year, month, and day values. One of it's tricks is the ability to roll forward to correct dates when given days and months that are "out of range".

What does the JavaScript Date () function do?

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

How do you convert a string to a date in JavaScript?

Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.


2 Answers

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

like image 170
Christian C. Salvadó Avatar answered Oct 09 '22 06:10

Christian C. Salvadó


// You might need both parts of it-

Date.fromDayofYear= function(n, y){     if(!y) y= new Date().getFullYear();     var d= new Date(y, 0, 1);     return new Date(d.setMonth(0, n)); } Date.prototype.dayofYear= function(){     var d= new Date(this.getFullYear(), 0, 0);     return Math.floor((this-d)/8.64e+7); }  var d=new Date().dayofYear(); // alert('day#'+d+' is '+Date.fromDayofYear(d).toLocaleDateString())   /*  returned value: (String) day#301 is Thursday, October 28, 2010 */ 
like image 22
kennebec Avatar answered Oct 09 '22 05:10

kennebec