Skip to the content

Lesson 66 of 296

Dates and JSON

What you will learn

  • Creating and reading dates
  • The month trap
  • Timestamps
  • Time zones and UTC
  • Formatting dates for users
  • Date libraries and the Temporal API
  • JSON in detail: stringify, parse and their options
On this page

Creating dates

const now = new Date();                          the current date and time
const fromString = new Date("2026-11-23T14:30:00Z");
const fromParts = new Date(2026, 10, 23, 14, 30);   year, month, day, hours, minutes
const fromTimestamp = new Date(1795000000000);

The month trap

In the parts form, months start at 0: January is 0 and December is 11.

new Date(2026, 0, 1)       1 January 2026
new Date(2026, 11, 25)     25 December 2026
new Date(2026, 12, 1)      1 January 2027 (it rolls over)

Days of the month start at 1, and getDay() (day of the week) starts at 0 for Sunday.

Reading parts of a date

MethodReturns
getFullYear()2026
getMonth()0 to 11
getDate()1 to 31 (day of the month)
getDay()0 (Sunday) to 6 (Saturday)
getHours(), getMinutes(), getSeconds()Time parts
getTime()The timestamp in milliseconds

These return the values in the user's local time zone. Methods like getUTCHours() return UTC values. Matching set... methods change a date (and mutate it).

Timestamps

A timestamp is the number of milliseconds since 1 January 1970, 00:00 UTC (called the Unix epoch).

Date.now()                1795000000000 (for example)

Timestamps are perfect for measuring time and comparing dates:

const start = Date.now();
doWork();
const ms = Date.now() - start;

Comparing dates:

dateA < dateB                           works (converted to numbers)
dateA.getTime() === dateB.getTime()     use this for equality; dateA === dateB compares references

Time zones and UTC

UTC (Coordinated Universal Time) is the world reference time. The UK uses UTC in winter and UTC+1 (BST) in summer.

A Date stores one moment in time (internally a UTC timestamp). How it is shown depends on the time zone.

Rules for real apps:

  1. Store dates in UTC, in ISO format or as timestamps, in the database and APIs.
  2. Convert to the user's local time only for display.
  3. Be careful with date-only values like birthdays: they are not moments in time, and converting them through time zones can shift them by a day. Store them as plain "YYYY-MM-DD" strings.
new Date().toISOString()       "2026-11-23T14:30:00.000Z"   (Z means UTC)

Parsing traps

new Date("2026-11-23")           treated as UTC midnight
new Date("2026-11-23T10:00")     treated as LOCAL time (no Z)
new Date("23/11/2026")           Invalid Date (format not supported reliably)

Only parse ISO 8601 strings (YYYY-MM-DDTHH:mm:ssZ). Other formats behave differently across browsers.

Check for invalid dates:

const d = new Date("rubbish");
Number.isNaN(d.getTime())        true

Formatting for users

Use Intl.DateTimeFormat or toLocaleDateString:

const d = new Date("2026-11-23T14:30:00Z");

d.toLocaleDateString("en-GB")                       "23/11/2026"
d.toLocaleDateString("en-US")                       "11/23/2026"
d.toLocaleDateString("en-GB", { dateStyle: "long" })   "23 November 2026"
d.toLocaleString("en-GB", { timeZone: "Europe/London" })   "23/11/2026, 14:30:00"

Never build date strings by hand with getDate() and getMonth() for users.

Relative times:

new Intl.RelativeTimeFormat("en-GB", { numeric: "auto" }).format(-1, "day")    "yesterday"

Date maths

const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);       handles month ends correctly

Adding 24 * 60 * 60 * 1000 milliseconds is not always one calendar day: clocks change twice a year, so some days are 23 or 25 hours long.

Libraries and Temporal

The built-in Date is known to be hard to use. In real projects, teams often use a library such as date-fns or Day.js for formatting and date maths.

A new built-in API called Temporal is being added to JavaScript to replace Date, with separate types for dates, times, time zones and durations. Support is arriving in browsers; check current support before using it without a polyfill. It is a good topic to mention in interviews to show you follow the language.

JSON in detail

JSON (JavaScript Object Notation) is the standard text format for sending data between servers and browsers.

JSON rules (stricter than JavaScript):

  • Keys must be in double quotes.
  • Strings must use double quotes.
  • No trailing commas.
  • No comments.
  • Allowed values: string, number, boolean, null, array, object. Not: undefined, functions, NaN, Infinity, dates, BigInt.
{
  "id": 7,
  "name": "Sam",
  "tags": ["admin", "editor"],
  "manager": null
}

JSON.stringify

JSON.stringify({ a: 1, b: "x" })        '{"a":1,"b":"x"}'
JSON.stringify(data, null, 2)           pretty-printed with 2-space indentation
JSON.stringify(user, ["id", "name"])    only these keys

What happens to special values:

ValueIn an objectIn an array
undefinedProperty removedBecomes null
FunctionProperty removedBecomes null
NaN, InfinityBecomes nullBecomes null
DateBecomes an ISO string (via its toJSON method)Same
Map, SetBecomes {}Same
BigIntThrows a TypeErrorSame

An object can control its own JSON output with a toJSON() method. That is how dates become strings.

JSON.parse

const obj = JSON.parse('{"id":7,"name":"Sam"}');

Invalid JSON throws a SyntaxError. Always wrap parsing of untrusted text in try...catch (Lesson 72):

try {
  const data = JSON.parse(text);
} catch {
  console.error("Invalid JSON");
}

Dates come back as strings, not Date objects. Convert them yourself, or use a reviver function:

const data = JSON.parse(text, (key, value) =>
  key === "createdAt" ? new Date(value) : value
);

Common mistakes

  • Month numbers starting at 1.
  • Parsing non-ISO date strings.
  • Storing local times instead of UTC.
  • Comparing dates with ===.
  • Expecting dates to survive a JSON round trip as Date objects.
  • Not catching JSON.parse errors.

How to say it in an interview

"A Date represents a single moment, stored as milliseconds since the Unix epoch in UTC. Months are zero-based. I store and transmit times in UTC as ISO strings, parse only ISO formats, and format for users with Intl.DateTimeFormat in their time zone. For heavy date logic I use a library like date-fns, and I am aware the Temporal API is coming to replace Date. JSON.stringify drops undefined and functions, turns dates into strings and throws on BigInt; JSON.parse throws on invalid input, so I wrap it in try-catch and convert date strings back when needed."

Key words

WordMeaning
TimestampMilliseconds since 1 January 1970 UTC
Unix epoch1 January 1970, 00:00:00 UTC
UTCThe world reference time
ISO 8601The standard date format, like 2026-11-23T14:30:00Z
Time zoneA region's local time offset from UTC
JSONA text format for data
SerialiseTurn data into text (JSON.stringify)
ParseTurn text back into data (JSON.parse)
ReviverA function that transforms values while parsing JSON

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.