AdvancedLesson 28 of 305 min read

Dates, times and Intl: formatting for any reader

Calculate with dates and show dates, numbers, currencies and relative times the way each reader expects using Intl.

In this lesson you will

  • Create, read and change Date objects
  • Calculate the difference between dates
  • Format dates and numbers with Intl
  • Handle time zones sensibly

About 21 minutes

Time is surprisingly tricky

“What day is it?” sounds simple until you remember time zones, daylight saving, months of different length, leap years, and countries that write dates in different orders. 03/04/2026 is the 4th of March in the United States and the 3rd of April in Pakistan. JavaScript gives you two tools to tame this: the Date object for calculating with moments in time, and the Intl toolkit for displaying dates, numbers and currencies the way each reader expects.

Creating dates

const now = new Date();                     // right now
const birthday = new Date(2000, 0, 15);      // year, month (0-11!), day
const fromText = new Date("2026-10-31T09:30:00");
const fromMs = new Date(1700000000000);

console.log(now.getFullYear());
console.log(birthday.getMonth());            // 0 = January
console.log(birthday.getDate(), birthday.getDay());   // day of month, weekday 0=Sunday
Good to know

Month numbers run from 0 to 11, while days of the month run from 1 to 31. It is a famous trap. Always double check when you pass or read a month.

Reading and changing parts

const d = new Date(2026, 9, 31, 14, 30);

console.log(d.getHours(), d.getMinutes());   // 14 30
d.setDate(d.getDate() + 7);                  // add a week (handles month ends)
console.log(d.toDateString());

d.setMonth(d.getMonth() + 1);
console.log(d.getMonth() + 1);               // human month number

Dates are numbers underneath

const a = new Date("2026-01-01");
const b = new Date("2026-12-25");

const diffMs = b - a;                        // subtraction gives milliseconds
const days = Math.round(diffMs / (1000 * 60 * 60 * 24));
console.log(days);                           // 358

console.log(a < b);                          // true: comparison works
console.log(Date.now());                     // ms since 1 Jan 1970 (UTC)

Write daysBetween(start, end) returning the whole number of days between two date strings, then print days from 2026-01-01 to 2026-03-01.

function daysBetween(start, end) {
  // your code
}
console.log(daysBetween('2026-01-01', '2026-03-01'));

Math.round((new Date(end) – new Date(start)) / 86400000)

function daysBetween(start, end) {
  const ms = new Date(end) - new Date(start);
  return Math.round(ms / (1000 * 60 * 60 * 24));
}
console.log(daysBetween('2026-01-01', '2026-03-01'));   // 59

Displaying dates for people: Intl.DateTimeFormat

const d = new Date(2026, 9, 31, 14, 30);

console.log(d.toLocaleDateString("en-US"));       // 10/31/2026
console.log(d.toLocaleDateString("en-GB"));       // 31/10/2026
console.log(d.toLocaleDateString("ur-PK"));       // Urdu formatting

console.log(d.toLocaleDateString("en-GB", {
  weekday: "long", day: "numeric", month: "long", year: "numeric"
}));                                              // Saturday 31 October 2026

console.log(new Intl.DateTimeFormat("en-GB", {
  dateStyle: "medium", timeStyle: "short"
}).format(d));                                    // 31 Oct 2026, 14:30

Never build date text by gluing pieces together (d.getDate() + "/" + d.getMonth()). It will be wrong for someone. Let Intl format it for the reader’s language and region, and pass undefined as the locale to use the visitor’s own browser setting.

Numbers and currency

const n = 1234567.891;

console.log(n.toLocaleString("en-US"));                   // 1,234,567.891
console.log(n.toLocaleString("de-DE"));                   // 1.234.567,891
console.log(n.toLocaleString("en-IN"));                   // 12,34,567.891

console.log(new Intl.NumberFormat("en-PK", {
  style: "currency", currency: "PKR"
}).format(2500));                                          // PKR 2,500.00

console.log(new Intl.NumberFormat("en-US", {
  style: "percent", maximumFractionDigits: 1
}).format(0.256));                                         // 25.6%

console.log(new Intl.NumberFormat("en", {
  notation: "compact"
}).format(1250000));                                       // 1.3M

Format the price 149999.5 as US dollars, as euros in German style, and the number 0.075 as a percentage with one decimal.

const price = 149999.5;
// print three formatted values

new Intl.NumberFormat(‘en-US’, { style: ‘currency’, currency: ‘USD’ }).format(price)

const price = 149999.5;
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price));
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(price));
console.log(new Intl.NumberFormat('en-US', { style: 'percent', minimumFractionDigits: 1 }).format(0.075));

Relative time: 3 days ago

const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

console.log(rtf.format(-1, "day"));      // yesterday
console.log(rtf.format(3, "day"));       // in 3 days
console.log(rtf.format(-2, "hour"));     // 2 hours ago

function timeAgo(date) {
  const seconds = Math.round((date - Date.now()) / 1000);
  const units = [["day", 86400], ["hour", 3600], ["minute", 60], ["second", 1]];
  for (const [unit, size] of units) {
    if (Math.abs(seconds) >= size || unit === "second") {
      return rtf.format(Math.round(seconds / size), unit);
    }
  }
}
console.log(timeAgo(new Date(Date.now() - 3 * 3600 * 1000)));   // 3 hours ago

Lists, plurals and sorting

console.log(new Intl.ListFormat("en", { type: "conjunction" })
  .format(["HTML", "CSS", "JavaScript"]));          // HTML, CSS, and JavaScript

const pr = new Intl.PluralRules("en");
console.log(pr.select(1), pr.select(5));            // one other

console.log(["z", "รค", "a"].sort((a, b) => a.localeCompare(b, "de")));   // sorted properly

Time zones

const meeting = new Date("2026-11-05T15:00:00Z");   // Z = UTC

for (const tz of ["Asia/Karachi", "Europe/London", "America/New_York"]) {
  console.log(tz, meeting.toLocaleString("en-GB", { timeZone: tz }));
}

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);   // the visitor's zone
  • Store and send dates as UTC (ISO format ending in Z), and convert to the visitor’s zone only when displaying.
  • new Date("2026-10-31") (date only) is read as UTC, while new Date("2026-10-31T00:00") is local time. This difference surprises many people.
  • For heavy date arithmetic (recurring events, business days) use a library such as date-fns or Day.js, or the newer built-in Temporal API as browsers add it.

Build a small countdown: print how many days, hours and minutes are left until the target date from the fixed ‘now’ provided.

const now = new Date('2026-10-31T09:00:00Z');
const target = new Date('2026-12-25T00:00:00Z');
// print days, hours, minutes left

const diff = target – now; days = Math.floor(diff / 86400000); then use the remainder for hours and minutes.

const now = new Date('2026-10-31T09:00:00Z');
const target = new Date('2026-12-25T00:00:00Z');
let diff = target - now;
const days = Math.floor(diff / 86400000);
diff -= days * 86400000;
const hours = Math.floor(diff / 3600000);
diff -= hours * 3600000;
const minutes = Math.floor(diff / 60000);
console.log(`${days} days, ${hours} hours, ${minutes} minutes left`);
Common mistake

Adding months by adding 30 days, or years by adding 365 days. Months and years vary. Use setMonth and setFullYear, which handle the calendar for you. And never format dates by hand when Intl can do it correctly.

Test with awkward dates

Try 31 January + 1 month, 29 February, and the days around daylight-saving changes. If your date code survives those, it is probably sound.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What number does January have in getMonth()?

  1. 1
  2. 12
  3. -1
  4. 0

Months run 0 to 11.

What does subtracting two Date objects give?

  1. Days
  2. Milliseconds
  3. A Date
  4. Text

The difference in milliseconds.

Which formats a number as currency?

  1. Math.currency
  2. String.money
  3. Date.format
  4. Intl.NumberFormat with style currency

Intl.NumberFormat handles currency.

What is the best way to store dates?

  1. In UTC, converting when displaying
  2. As local text
  3. As the visitor’s time zone
  4. As words

UTC avoids confusion across zones.

Why avoid building date text manually with getDate and getMonth?

  1. It is slower
  2. It is invalid
  3. Formats and languages differ, and Intl handles them
  4. Dates cannot be text

Intl respects the reader’s locale.

Summary

  • Months start at 0.
  • Subtract dates to get milliseconds.
  • Intl formats dates, numbers and currency for any locale.
  • Store UTC, display local.

Next lesson

Next: the browser’s built-in Web APIs, observers, clipboard, canvas and more.

Questions

Why is my date one day off?

A date-only string is read as UTC, then shown in your local zone. Include a time, or format in UTC.

Do I need a library like Moment.js?

No. Intl and modern built-ins cover most needs. For heavy date maths, date-fns or Day.js are light alternatives.

What is the Temporal API?

A new built-in date and time API designed to fix Date's problems. Browser support is growing; check before using.

Progress is saved in this browser.