JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

40. Dates (Date)

This chapter describes JavaScript’s API for working with dates – Date.

40.1. Best practice: don’t use the current built-in API

The JavaScript Date API is cumbersome to use. Hence, it’s best to rely on a library for anything related to dates. Popular libraries include:

Consult the blog post “Why you shouldn’t use Moment.js…” for the pros and cons of these libraries.

Additionally, TC39 is working on a new date API for JavaScript: temporal.

40.2. Background: UTC vs. GMT

UTC (Coordinated Universal Time) and GMT (Greenwich Mean Time) have the same current time, but they are different things:

Source: “The Difference Between GMT and UTC” at

40.3. Background: date time formats (ISO)

Date time formats describe:

The following is an example of a date time string returned by .toISOString():


Date time formats have the following structures:

Alternative to Z – time zones relative to UTC:

40.4. Time values

A time value represents a date via the number of milliseconds since 1 January 1970 00:00:00 UTC.

Time values can be used to create Dates:

const timeValue = 0;
  new Date(timeValue).toISOString(),

Coercing a Date to a number returns its time value:

> Number(new Date(123))

Ordering operators coerce their operands to numbers. Therefore, you can use these operators to compare Dates:

assert.equal(new Date('1972-05-03') < new Date('2001-12-23'), true);
// Internally:
assert.equal(73699200000 < 1009065600000, true);

40.4.1. Creating time values

The following methods create time values:

40.4.2. Getting and setting time values

40.5. Creating Dates

40.6. Getters and setters

40.6.1. Time unit getters and setters

Dates have getters and setters for time units. For example:

These getters and setters conform to the following patterns:

These are the time units that are supported:

There is one more getter that doesn’t conform to the previously mentioned patterns:

40.7. Converting Dates to strings

Example Date:

const d = new Date(0);

40.7.1. Strings with times

40.7.2. Strings with dates

40.7.3. Strings with dates and times

  Exercise: Creating a date string


40.8. Pitfalls of the Date API