ECMA compliant implementations use the extended Gregorian system for dates. These are all based on 01-January-1970 UTC as a starting point. Although the date handling in JavaScript is flexible and generally comprehensive, there may be additional date computations required in some implementations.
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 from 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))
The month value is worked out with this formulaic framework:
MonthFromTime(t) = lookup according to DayWithinYear(t) falling into a range according to the following table:
Greater than | Less than | Month | Name |
000 | 031 | 0 | January |
031 | 059 + InLeapYear(t) | 1 | February |
059 + InLeapYear(t) | 090 + InLeapYear(t) | 2 | March |
090 + InLeapYear(t) | 120 + InLeapYear(t) | 3 | April |
120 + InLeapYear(t) | 151 + InLeapYear(t) | 4 | May |
151 + InLeapYear(t) | 181 + InLeapYear(t) | 5 | June |
181 + InLeapYear(t) | 212 + InLeapYear(t) | 6 | July |
212 + InLeapYear(t) | 243 + InLeapYear(t) | 7 | August |
243 + InLeapYear(t) | 273 + InLeapYear(t) | 8 | September |
273 + InLeapYear(t) | 304 + InLeapYear(t) | 9 | October |
304 + InLeapYear(t) | 334 + InLeapYear(t) | 10 | November |
334 + InLeapYear(t) | 365 + InLeapYear(t) | 11 | December |
The date within the month is worked out in a similar way, and could probably share a common table of month lengths or offsets.
DateFromTime(t) = lookup according to MonthFromTime(t) selecting a value to subtract according to the following table:
Prev | Home | Next |
Date constant | Up | Date 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. |