# 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 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:

 Month value Subtract this 00 -1 01 30 02 58 + InLeapYear(t) 03 89 + InLeapYear(t) 04 119 + InLeapYear(t) 05 150 + InLeapYear(t) 06 180 + InLeapYear(t) 07 211 + InLeapYear(t) 08 242 + InLeapYear(t) 09 272 + InLeapYear(t) 10 303 + InLeapYear(t) 11 333 + 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