Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.5 — Formatting Numbers and Dates
JavaScript · Example 2 of 3

Dates and times on different clocks

Every formatter here names its timeZone, so the output is the same on every computer. Leave timeZone out and each visitor sees the moment on their own clock.

The built-in Intl object formats numbers, money, percentages, units, dates and times the way each language and country expects: Intl.NumberFormat, Intl.DateTimeFormat and the toLocaleString shortcuts, plus helpers for relative times, lists, plurals and sorting.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write formatINR(paise) that takes whole paise and returns rupees formatted for India, so formatINR(123456789) returns ₹12,34,567.89.

02

Write fileSize(bytes) that shows 512 B, 1.5 kB or 2.3 MB with Intl.NumberFormat and its unit style (use 1000 per step and one decimal).

03

Write timeAgo(minutes) that returns text like 5 minutes ago or 2 hours ago with Intl.RelativeTimeFormat, switching to hours from 60 minutes.

Explain it without notes

01

Why should formatting happen only at display time?

02

What does a locale like en-IN control in Intl.NumberFormat?

03

Why can two computers show different results for date.toLocaleString(), and how do you make them match?

04

When would you use Intl.Collator instead of the default sort?

Dates and times on different clocks

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

US, UTC: 1/15/2024
UK, UTC: 15/01/2024
full: Monday, January 15, 2024
medium + short: 15 Jan 2024, 10:30
India: 15 Jan 2024, 4:00 pm
Tokyo, 24h: 19:30
parts: Mon, January 15, 2024
Hindi: सोमवार, 15 जनवरी 2024
shortcut: 15.1.2024