Date from time (Time calculation)

A date and time algorithm defined by ECMAScript.

Availability:

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

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 thanLess thanMonthName
0000310January
031059 + InLeapYear(t)1February
059 + InLeapYear(t)090 + InLeapYear(t)2March
090 + InLeapYear(t)120 + InLeapYear(t)3April
120 + InLeapYear(t)151 + InLeapYear(t)4May
151 + InLeapYear(t)181 + InLeapYear(t)5June
181 + InLeapYear(t)212 + InLeapYear(t)6July
212 + InLeapYear(t)243 + InLeapYear(t)7August
243 + InLeapYear(t)273 + InLeapYear(t)8September
273 + InLeapYear(t)304 + InLeapYear(t)9October
304 + InLeapYear(t)334 + InLeapYear(t)10November
334 + InLeapYear(t)365 + InLeapYear(t)11December

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:

Month valueSubtract this
00-1
0130
0258 + InLeapYear(t)
0389 + InLeapYear(t)
04119 + InLeapYear(t)
05150 + InLeapYear(t)
06180 + InLeapYear(t)
07211 + InLeapYear(t)
08242 + InLeapYear(t)
09272 + InLeapYear(t)
10303 + InLeapYear(t)
11333 + InLeapYear(t)

See also:Broken down time, Date number, Day from year, Day number, Day within year, Month from time, Time from year, Time range, Year from time

Cross-references:

ECMA 262 edition 2 - section - 15.9.1.5

ECMA 262 edition 3 - section - 15.9.1.5