JavaScript Functions and Methods: A Topic-by-Topic Reference · Lesson 10 of 12

Lesson 10: Date and JSON

Creating dates, getters and setters, formatting, date arithmetic, UTC, JSON.stringify and JSON.parse with replacers, and localStorage.

Lesson 10: Date and JSON

Dates

A Date holds one moment in time (milliseconds since 1 January 1970 UTC). Be careful with time zones: examples here use UTC so the results are the same everywhere.

Creating a Date

From text, from parts (month starts at 0), from a timestamp, or now.

console.log(new Date("2026-10-04T10:30:00Z").toISOString());
console.log(new Date(Date.UTC(2026, 9, 4)).toISOString());
console.log(new Date(0).toISOString());
console.log(typeof Date.now());

Output:

2026-10-04T10:30:00.000Z
2026-10-04T00:00:00.000Z
1970-01-01T00:00:00.000Z
number

Getting parts

Use the UTC getters for time-zone-proof results. getUTCMonth() is 0 for January; getUTCDay() is 0 for Sunday.

const d = new Date(Date.UTC(2026, 9, 4, 14, 30));
console.log(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
console.log(d.getUTCHours(), d.getUTCMinutes(), d.getUTCDay());
console.log(d.getTime());

Output:

2026 9 4
14 30 0
1791124200000

Date arithmetic

Change a date with the setters, or subtract two dates to get milliseconds.

const d = new Date(Date.UTC(2026, 9, 4));
d.setUTCDate(d.getUTCDate() + 30);
console.log(d.toISOString().slice(0, 10));
const a = new Date("2026-10-04"), b = new Date("2026-12-25");
console.log(Math.round((b - a) / 86400000), "days");

Output:

2026-11-03
82 days

Comparing and sorting dates

Dates compare by value with < and > (not ===).

const x = new Date("2026-01-01"), y = new Date("2026-06-01");
console.log(x < y, x.getTime() === new Date("2026-01-01").getTime());
console.log([y, x].sort((a, b) => a - b).map((d) => d.toISOString().slice(0, 10)));

Output:

true true
[ '2026-01-01', '2026-06-01' ]

Formatting

toISOString is exact and sortable. toLocaleDateString and Intl.DateTimeFormat format for people.

const d = new Date(Date.UTC(2026, 9, 4, 14, 30));
console.log(d.toISOString());
console.log(d.toLocaleDateString("en-GB", { timeZone: "UTC", day: "numeric", month: "long", year: "numeric" }));
console.log(new Intl.DateTimeFormat("en-US", { timeZone: "UTC", dateStyle: "long" }).format(d));

Output:

2026-10-04T14:30:00.000Z
4 October 2026
October 4, 2026

Now and today (not run)

These change every second.

console.log(new Date());
console.log(Date.now());
console.log(new Date().toLocaleDateString());

Parsing text like "10/04/2026" depends on the browser and region. Store and send dates as ISO text (2026-10-04 or 2026-10-04T10:30:00Z). For Nepali (BS) dates, convert with a tested library.

JSON

JSON.stringify(value)

Object to text. Functions, undefined and symbols are dropped; dates become ISO text.

const data = { name: "Sita", marks: [80, 92], passed: true, note: null, skip: undefined, fn() {}, when: new Date(0) };
console.log(JSON.stringify(data));

Output:

{"name":"Sita","marks":[80,92],"passed":true,"note":null,"when":"1970-01-01T00:00:00.000Z"}

JSON.parse(text)

Text to object. Invalid JSON throws an error, so wrap untrusted input in try/catch.

const obj = JSON.parse('{"a": [1, 2, {"b": true}]}');
console.log(obj.a[2].b);
try { JSON.parse("{bad json}"); } catch (e) { console.log(e.name); }

Output:

true
SyntaxError

Pretty printing and picking fields

The third argument adds indentation; the second can be a list of keys to keep.

const user = { id: 1, name: "Ram", password: "secret" };
console.log(JSON.stringify(user, null, 2));
console.log(JSON.stringify(user, ["id", "name"]));

Output:

{
  "id": 1,
  "name": "Ram",
  "password": "secret"
}
{"id":1,"name":"Ram"}

replacer and reviver functions

Transform values while writing or reading JSON, for example to restore dates.

const text = JSON.stringify({ when: new Date(Date.UTC(2026, 0, 1)), n: 5 });
console.log(text);
const back = JSON.parse(text, (key, v) => (key === "when" ? new Date(v) : v));
console.log(back.when instanceof Date, back.when.getUTCFullYear());

Output:

{"when":"2026-01-01T00:00:00.000Z","n":5}
true 2026

Deep clone with JSON (and its limits)

A quick copy for plain data. It loses dates, undefined, Maps and Sets: prefer structuredClone.

const a = { x: [1, 2], d: new Date(0), u: undefined };
console.log(JSON.parse(JSON.stringify(a)));
console.log(structuredClone(a));

Output:

{ x: [ 1, 2 ], d: '1970-01-01T00:00:00.000Z' }
{ x: [ 1, 2 ], d: 1970-01-01T00:00:00.000Z, u: undefined }

Storing data in the browser

localStorage and sessionStorage

Keep small amounts of text in the browser. Store objects as JSON. (Browser only: shown, not run.)

localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));
localStorage.setItem("user", JSON.stringify({ name: "Sita", marks: [80, 92] }));
const user = JSON.parse(localStorage.getItem("user") ?? "null");
localStorage.removeItem("theme");

fetch and JSON (not run)

Ask a server for data and read it as JSON. Needs a network.

async function loadUsers() {
  const res = await fetch("https://example.com/api/users");
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}
loadUsers().then(console.log).catch(console.error);

Try it yourself

  1. Write a function that returns the number of days between two ISO date strings.
  2. Save an array of objects to localStorage and load it back.
  3. Convert an object to JSON and back, and compare with the original.

Next lesson: Promises and async code.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 10: Date and JSON | MeroSir