JavaScript time values: dates as milliseconds since 1970-01-01

[2014-02-14] dev, javascript, jslang
(Ad, please don’t block)
This blog post explains how JavaScript dates are stored internally as time values, milliseconds since 1970-01-01.

What the date API calls time is called a time value by the ECMAScript specification. It is a primitive number that encodes a date as milliseconds since 1 January 1970 00:00:00 UTC. Each date object stores its state as a time value, in the internal property [[PrimitiveValue]] (the same property that instances of the wrapper constructors Boolean, Number, and String use to store their wrapped primitive values).

Warning: Leap seconds are ignored in time values.

The following methods work with time values:

  • new Date(timeValue) uses a time value to create a date.
  • Date.parse(dateTimeString) parses a string with a date time string and returns a time value.
  • Date.now() returns the current date time as a time value.
  • Date.UTC(year, month, date?, hours?, minutes?, seconds?, milliseconds?) interprets the parameters relative to UTC and returns a time value.
  • Date.prototype.getTime() returns the time value stored in the receiver.
  • Date.prototype.setTime(timeValue) changes the date as specified via a time value.
  • Date.prototype.valueOf() returns the time value stored in the receiver. This method determines how dates are converted to primitives, as explained in the next subsection.
The range of JavaScript integers (53 bits plus a sign, see [1]) is large enough that a time span can be represented that starts at approximately 285,616 years before 1970 and ends at approximately 285,616 years after 1970.

A few examples of converting dates to time values:

    > new Date('1970-01-01').getTime()
    0
    > new Date('1970-01-02').getTime()
    86400000
    > new Date('1960-01-02').getTime()
    -315532800000
The Date constructor enables you to convert times values to dates:
    > new Date(0)
    Date {Thu Jan 01 1970 01:00:00 GMT+0100 (CET)}
    > new Date(24 * 60 * 60 * 1000)  // 1 day in ms
    Date {Fri Jan 02 1970 01:00:00 GMT+0100 (CET)}
    > new Date(-315532800000)
    Date {Sat Jan 02 1960 01:00:00 GMT+0100 (CET)}

Converting a Date to a Number

A date is converted to a number [2] via Date.prototype.valueOf(), which returns a time value. This allows you to compare dates:
    > new Date('1980-05-21') > new Date('1980-05-20')
    true
You can also perform arithmetic, but beware that leap seconds are ignored:
    > new Date('1980-05-21') - new Date('1980-05-20')
    86400000

Reference

  1. What are integers in JavaScript?
  2. Coercing objects to primitives