In leap year (Time calculation)

A date and time algorithm defined by ECMAScript.

Availability:

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

It is useful to know whether you are in a leap year. ECMA compliant implementations use an extended Gregorian system to compute dates and can compute leap year flag values internally. This facility may not be available within scripts in all implementations. It can be simulated however.

ECMA compliant implementations use an extended Gregorian system to map a day number to a year number and to determine the month and date within that year. In this system, leap years are summarized thus:

DaysInYear(y) =

365 if ((y modulo 4) != 0)

366 if ((y modulo 4) == 0) and ((y modulo 100) != 0)

365 if ((y modulo 4) == 0) and ((y modulo 400) != 0)

366 if ((y modulo 400) == 0)

All non-leap-years 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)

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

This leap year method would yield a 1 for years that are leap years and 0 for the others:

InLeapYear(y) = 0 if DaysInYear(y) == 365

= 1 if DaysInYear(y) == 366

To use a time value instead of a year number, the function can be modified like this:

InLeapYear(t) = 0 if DaysInYear(YearFromTime(t)) == 365

= 1 if DaysInYear(YearFromTime(t)) == 366

Example code:

   // Test for leap year

   document.write("<TABLE BORDER=1>");

   for(ii=1980; ii<2009; ii++)

   {

   document.write("<TR><TD>");

   document.write(ii);

   document.write("</TD><TD>");

   document.write(inLeapYear(ii));

   document.write("</TD></TR>");

   }

   document.write("</TABLE>");

   // Flag a leap year with a Boolean value

   function inLeapYear(aYear)

   {

   if((aYear % 4) != 0)

   {

   return false;

   }

   

   if(((aYear % 100) != 0) ||

   ((aYear % 400) == 0))

   {

   return true;

   }

   

   return false;

   }

See also:Day from year, Days in year, Time range, 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