Time from year (Time calculation)

A date and time algorithm defined by ECMAScript.

Availability:

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

To calculate any time values relative to the start of a year, we need to know what instant the year began.

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) msPerDay = 86400000 TimeFromYear(y) = msPerDay * DayFromYear(y)

Subtracting this value from any absolute time value gives you a millisecond accurate offset from the beginning of the specified year.

Example code:

```   // Work out days and milliseconds at start of a year
var msPerDay = 86400000;

// Test day from year
document.write("<TABLE BORDER=1>");
for(var ii=1980; ii<2009; ii++)
{
document.write("<TR>");
document.write("<TD>");
document.write(ii);
document.write("</TD>");
document.write("<TD>");
document.write(dayFromYear(ii));
document.write("</TD>");
document.write("<TD>");
document.write(timeFromYear(ii));
document.write("</TD>");
document.write("</TR>");
}
document.write("</TABLE>");

// Work out milliseconds at start of year
function timeFromYear(aYear)
{
var myTime = msPerDay * dayFromYear(aYear);
return myTime;
}

// Day from year function
function dayFromYear(aYear)
{
var 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, Day within year, Time range, Time within day, Year from time, Year number

Cross-references:

ECMA 262 edition 2 - section - 15.9.1.3

ECMA 262 edition 3 - section - 15.9.1.3