We need to calculate a reference point for each year number to know when it starts. We do this by calculating the number of days since the timer started.
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:
DayFromYear(y) =
365 * (y - 1970) +
floor((y - 1969) / 4) -
floor((y - 1901) / 100) +
floor((y - 1601) / 400)
This function will return the start day for the year number passed in as an argument. See the example code to see how to run this in a test harness.
// 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("</TR>"); } document.write("</TABLE>"); // 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; }
Prev | Home | Next |
Date.valueOf() | Up | Day number |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |