Given a time value, it is helpful to be able to compute a year number from it. The ECMA compliant implementations use the extrapolated Gregorian system to map days to years and compute a time relative to the reference date of 01-January-1970 UTC. From there the year number can be established.
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)
YearFromTime(t) = The largest integer y to make TimeFromYear(y) less than or equal to t.
// Work out year number from time var msPerDay = 86400000; var myMilliseconds = Number(new Date()); document.write(yearFromTime(myMilliseconds)); // Return year number based on time value function yearFromTime(aMilliseconds) { var myStartYear = 1970; while(timeFromYear(myStartYear) < myMilliseconds) { myStartYear++ } return myStartYear-1; } // Work out milliseconds at start of year function timeFromYear(aYear) { var myTime = msPerDay * dayFromYear(aYear); return myTime; } // Work out day number from milliseconds function dayNumber(aMillisecondTime) { var myDay = Math.floor(aMillisecondTime/msPerDay); return myDay; } // 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 |
Y | Up | Year 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. |