Day within year (Time calculation)

A date and time algorithm defined by ECMAScript.

Availability:

ECMAScript edition - 2
Property/method value type:Number primitive

The day number within a year is calculated by subtracting the day at the start of the year from the target day being evaluated. The difference is the day number within its year.

The formula for calculating day number is shown here:

t = an instant in time measured in milliseconds relative to 01-January-1970 UTC.

msPerDay = 86400000

Day(t) = floor(t/msPerDay)

All non-leap years have 365 days with the usual number of days in each month. Leap years have an extra day in February. The calculation shown below uses known leap years and non-leap years to adjust the day numbers and yield the day number of the first day of the given year and then use that to work out the time in milliseconds when the year started:

DayFromYear(y) =

365 * (y - 1970) +

floor((y - 1969) / 4) -

floor((y - 1901) / 100) +

floor((y - 1601) / 400)

TimeFromYear(y) = msPerDay * DayFromYear(y)

YearFromTime(t) = The largest integer y to make TimeFromYear(y) less than or equal to t.

DayWithinYear(t) = Day(t) - DayFromYear(YearFromTime(t))

Example code:

   // Work out a day number within the year
   msPerDay = 86400000;
   myMilliseconds = Number(new Date());
   document.write(dayWithinYear(myMilliseconds));
   // Work out day number within year based on time value
   function dayWithinYear(aMilliseconds)
   {
   myDayNumber     = dayNumber(aMilliseconds);
   myYearFromTime  = yearFromTime(aMilliseconds);
   myDayFromYear   = dayFromYear(myYearFromTime);
   myDayWithinYear = myDayNumber - myDayFromYear;
   
   return myDayWithinYear;
   }
   // Return year number based on time value
   function yearFromTime(aMilliseconds)
   {
   myStartYear = 1970;
   
   while(timeFromYear(myStartYear) < myMilliseconds)
   {
   myStartYear++
   }
   
   return myStartYear-1;
   }
   // Work out milliseconds at start of year
   function timeFromYear(aYear)
   {
   myTime = msPerDay * dayFromYear(aYear);
   return myTime;
   }
   // Work out day number from milliseconds
   function dayNumber(aMillisecondTime)
   {
   myDay = Math.floor(aMillisecondTime/msPerDay);
   
   return myDay;
   }
   // Day from year function
   function dayFromYear(aYear)
   {
   myDay = 365 * (aYear - 1970)             +
   Math.floor((aYear - 1969) / 4)   -
   Math.floor((aYear - 1901) / 100) +
   Math.floor((aYear - 1601) / 400);
   return myDay;
   }

See also:Broken down time, Date from time, Date number, Day from year, Day number, Month from time, Month number, Time from year, Year from time

Cross-references:

ECMA 262 edition 2 - section - 15.9.1.4

ECMA 262 edition 3 - section - 15.9.1.4