tags:

views:

50

answers:

4

I want to take a day of the year and convert to an actual date using the Date object. How can I go about doing this?

A: 

If I understand your question correctly, you can do that from the Date constructor like this

new Date(year, month, day, hours, minutes, seconds, milliseconds)

All arguments as integers

castis
+1  A: 

You have a few options;

If you're using a standard format, you can do something like:

new Date(dateStr);

If you'd rather be safe about it, you could do:

var date, timestamp;
try {
    timestamp = Date.parse(dateStr);
} catch(e) {}
if(timestamp)
    date = new Date(timestamp);

or simply,    

new Date(Date.parse(dateStr));

Or, if you have an arbitrary format, split the string/parse it into units, and do:

new Date(year, month - 1, day)

Example of the last:

var dateStr = '28/10/2010'; // uncommon US short date
var dateArr = dateStr.split('/');
var dateObj = new Date(dateArr[2], parseInt(dateArr[1]) - 1, dateArr[0]);
mway
sorry.. meant if I had a specific day of the year. example: lets say its day 232 of year 1995... how can I construct a new Date out of it?
croteau
+2  A: 

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

CMS
A: 

// 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
*/
kennebec
sorry.. meant if I had a specific day of the year. example: lets say its day 232 of year 1995... how can I construct a new Date out of it?
croteau
var d=Date.fromDayofYear(232,1995)
kennebec