Faqts : Computers : Programming : Languages : JavaScript : Language Core : Dates

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

10 of 13 people (77%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I compute the day of the year for a given Date?

May 26th, 2001 02:05
Martin Honnen,


Here is the solution which exploits that the JavaScript Date objects 
rolls Date components i.e. if you set the day to 0 the month is 
decreased by one and the day is set to last day in the month.
function dayOfYear (date) {
  var day = 0;
  day += date.getDate();
  var month = date.getMonth();
  while (month) {
    date.setDate(0);
    day += date.getDate();
    month = date.getMonth();
  }
  return day
}
var d1 = new Date();
alert(dayOfYear(d1))