# Date Formatting and Time Zones

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Dates and Times
Source: https://www.devtutorials.ai/learn/javascript/dates/date-formatting-and-time-zones

> Showing dates with toString, toDateString and toISOString, formatting for people with Intl.DateTimeFormat, locales, dateStyle and timeStyle, the timeZone option and getTimezoneOffset, and filtering and comparing dates in a half-open range.

## What Is Date Formatting?

**Formatting** = turning a date's stored number into text people can read.

- **Locale** = the language and country style, like `"en-IN"` or `"en-US"`.
- **Time zone** = which clock to read, like `"Asia/Kolkata"`.
- A date stores a **moment**. The time zone only matters when you make text.

**Simple lesson:** one moment, many ways to write it. You choose the language and the clock.

### A Real-World Example

A sale ends at `2026-09-01T18:30:00Z`.
A customer in Mumbai should see **2 September, 12:00 am**.
A customer in New York should see **September 1, 2:30 PM**. Same moment, different clocks.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="One moment in the middle sends lines to three clocks: London, Mumbai and New York, each showing a different local time." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="200" y="20" width="160" height="40" rx="8" fill="#1e3a8a" />
    <text x="280" y="45" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#ffffff">18:30Z, 1 Sep</text>
    <line x1="280" y1="60" x2="95" y2="110" stroke="#94a3b8" strokeWidth="2" strokeDasharray="5 4"><animate attributeName="stroke-dashoffset" values="30;0" dur="1.5s" repeatCount="indefinite" /></line>
    <line x1="280" y1="60" x2="280" y2="110" stroke="#94a3b8" strokeWidth="2" strokeDasharray="5 4"><animate attributeName="stroke-dashoffset" values="30;0" dur="1.5s" repeatCount="indefinite" /></line>
    <line x1="280" y1="60" x2="465" y2="110" stroke="#94a3b8" strokeWidth="2" strokeDasharray="5 4"><animate attributeName="stroke-dashoffset" values="30;0" dur="1.5s" repeatCount="indefinite" /></line>
    <rect x="20" y="110" width="150" height="44" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="95" y="130" textAnchor="middle" fontSize="11" fill="#1e40af">London</text>
    <text x="95" y="146" textAnchor="middle" fontSize="12" fill="#1e40af">19:30, 1 Sep</text>
    <rect x="205" y="110" width="150" height="44" rx="8" fill="#fff7ed" stroke="#ea580c" />
    <text x="280" y="130" textAnchor="middle" fontSize="11" fill="#9a3412">Mumbai</text>
    <text x="280" y="146" textAnchor="middle" fontSize="12" fill="#9a3412">00:00, 2 Sep</text>
    <rect x="390" y="110" width="150" height="44" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="465" y="130" textAnchor="middle" fontSize="11" fill="#166534">New York</text>
    <text x="465" y="146" textAnchor="middle" fontSize="12" fill="#166534">14:30, 1 Sep</text>
  </svg>
  <figcaption>The moment is the same. Only the clock it is read on changes.</figcaption>
</figure>

"Now" is frozen at **1 September 2026, 12:00 UTC** in these boxes. One box fails on purpose; its title says so.

## What You Will Learn

1. The built-in text methods: `toString()`, `toDateString()`, `toISOString()`.
2. `Intl.DateTimeFormat` with a locale, `dateStyle` and `timeStyle`.
3. The `timeZone` option and `getTimezoneOffset()`.
4. How to filter and compare dates in a range.

## Date formatting basics

### Displaying dates in readable form

- **For machines** (saving, sending): `toISOString()`. Same text everywhere.
- **For people** (showing on screen): `Intl.DateTimeFormat`, with a locale and time zone.

```js runnable title="The same moment, as machine text and as people text"
const saleEnds = new Date("2026-09-01T18:30:00Z");
console.log(saleEnds.toISOString());
console.log(new Intl.DateTimeFormat("en-IN", { dateStyle: "long", timeStyle: "short", timeZone: "Asia/Kolkata" }).format(saleEnds));
```

Expected output:

```text
2026-09-01T18:30:00.000Z
2 September 2026 at 12:00 am
```

### `toString()`

Uses **your computer's** time zone. Good for quick checks, not for customers.

```js runnable title="toString() uses this computer's time zone"
console.log(new Date("2026-09-01T18:30:00Z").toString());
```

### `toDateString()`

Drops the time, but still uses local time, so the day can differ by computer.

```js runnable title="toDateString() drops the time, but still uses local time"
console.log(new Date("2026-09-01T18:30:00Z").toDateString());
```

### `toISOString()`

Always UTC, always the same. `slice(0, 10)` gives the date, `slice(11, 19)` the time. `JSON.stringify` uses the same format for dates.

```js runnable title="toISOString() is the same everywhere, and can be sliced"
const d = new Date("2026-09-01T18:30:00Z");
console.log(d.toISOString());
console.log(d.toISOString().slice(0, 10), d.toISOString().slice(11, 19));
console.log(JSON.stringify({ placedAt: d }));
```

Expected output:

```text
2026-09-01T18:30:00.000Z
2026-09-01 18:30:00
{"placedAt":"2026-09-01T18:30:00.000Z"}
```

## Intl.DateTimeFormat

Make a formatter once with your choices, then call `.format(date)` as often as you like.

```js runnable title="Create a formatter, then format a date with it"
const fmt = new Intl.DateTimeFormat("en-IN", { dateStyle: "medium", timeZone: "UTC" });
console.log(fmt.format(new Date("2026-09-01T00:00:00Z")));
console.log(fmt.format(new Date("2026-12-25T00:00:00Z")));
```

Expected output:

```text
1 Sept 2026
25 Dec 2026
```

### Formatting with locale

The locale decides the language and the order of day, month and year.

```js runnable title="One moment, five locales"
const d = new Date("2026-09-01T00:00:00Z");
for (const locale of ["en-IN", "en-US", "en-GB", "hi-IN", "ja-JP"]) {
  console.log(locale, new Intl.DateTimeFormat(locale, { dateStyle: "long", timeZone: "UTC" }).format(d));
}
```

Expected output:

```text
en-IN 1 September 2026
en-US September 1, 2026
en-GB 1 September 2026
hi-IN 1 सितंबर 2026
ja-JP 2026年9月1日
```

Browsers can differ in small details, such as `Sep` or `Sept`. Never compare formatted text in code; compare dates.

### dateStyle

Four sizes: `"full"`, `"long"`, `"medium"` and `"short"`.

```js runnable title="The four date styles in British English"
const d = new Date("2026-09-01T00:00:00Z");
for (const style of ["full", "long", "medium", "short"]) {
  console.log(style, new Intl.DateTimeFormat("en-GB", { dateStyle: style, timeZone: "UTC" }).format(d));
}
```

Expected output:

```text
full Tuesday, 1 September 2026
long 1 September 2026
medium 1 Sept 2026
short 01/09/2026
```

### timeStyle

The same four sizes for the clock. Use both styles for a date and a time.

```js runnable title="Two time styles, and a date and time together"
const d = new Date("2026-09-01T18:30:00Z");
console.log(new Intl.DateTimeFormat("en-GB", { timeStyle: "short", timeZone: "UTC" }).format(d));
console.log(new Intl.DateTimeFormat("en-GB", { timeStyle: "medium", timeZone: "UTC" }).format(d));
console.log(new Intl.DateTimeFormat("en-GB", { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" }).format(d));
```

Expected output:

```text
18:30
18:30:00
1 Sept 2026, 18:30
```

You cannot mix a style with single parts like `month`:

```js runnable expect-error title="dateStyle and a separate month option cannot be combined"
new Intl.DateTimeFormat("en-GB", { dateStyle: "long", month: "short" }).format(new Date());
```

## Time zones

### Formatting with timeZone

`timeZone` picks the clock. The stored moment does not change.

```js runnable title="One moment, four wall clocks"
const saleEnds = new Date("2026-09-01T18:30:00Z");
for (const zone of ["UTC", "Europe/London", "Asia/Kolkata", "America/New_York"]) {
  const text = new Intl.DateTimeFormat("en-GB", { dateStyle: "medium", timeStyle: "short", timeZone: zone }).format(saleEnds);
  console.log(zone.padEnd(17), text);
}
```

Expected output:

```text
UTC               1 Sept 2026, 18:30
Europe/London     1 Sept 2026, 19:30
Asia/Kolkata      2 Sept 2026, 00:00
America/New_York  1 Sept 2026, 14:30
```

### getTimezoneOffset()

Minutes between UTC and **your** clock. The sign is backwards: India (UTC+5:30) gives `-330`.

```js runnable title="The offset and the zone name of this computer"
console.log(new Date().getTimezoneOffset());
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
```

### How time zones affect output

A customer picks 1 September. Shown in New York's clock, midnight UTC is still 31 August there.

```js runnable title="A date picked by a user, shown back in New York"
const picked = new Date("2026-09-01");
const opts = { dateStyle: "long" };
console.log(new Intl.DateTimeFormat("en-US", { ...opts, timeZone: "UTC" }).format(picked));
console.log(new Intl.DateTimeFormat("en-US", { ...opts, timeZone: "America/New_York" }).format(picked));
```

Expected output:

```text
September 1, 2026
August 31, 2026
```

For a date with no time (a birthday, a delivery day), format it with `timeZone: "UTC"`.

## Working with date ranges

### Start and end dates

Use a **half-open** range: from the start of this month, up to (not including) the start of next month.

```js runnable title="The start of a month and the start of the next one"
const start = new Date(Date.UTC(2026, 8, 1));
const end = new Date(Date.UTC(2026, 9, 1));
console.log(start.toISOString());
console.log(end.toISOString());
```

Expected output:

```text
2026-09-01T00:00:00.000Z
2026-10-01T00:00:00.000Z
```

### Filtering a date range

Keep `placed >= start && placed < end`. An order late on the last day still counts.

```js runnable title="Orders placed in September, including one late on 30 September"
const orders = [
  { id: 1, placedAt: "2026-08-31T23:00:00Z" },
  { id: 2, placedAt: "2026-09-01T00:00:00Z" },
  { id: 3, placedAt: "2026-09-30T22:45:00Z" },
  { id: 4, placedAt: "2026-10-01T00:00:00Z" },
];
const start = new Date(Date.UTC(2026, 8, 1));
const end = new Date(Date.UTC(2026, 9, 1));
const september = orders.filter((o) => {
  const placed = new Date(o.placedAt);
  return placed >= start && placed < end;
});
console.log(september.map((o) => o.id).join(", "));

const wrongEnd = new Date(Date.UTC(2026, 8, 30));
console.log(orders.filter((o) => new Date(o.placedAt) >= start && new Date(o.placedAt) <= wrongEnd).map((o) => o.id).join(", "));
```

Expected output:

```text
2, 3
2
```

The second filter ends at midnight on 30 September, so it loses order 3.

### Comparing dates

- `<`, `>`, `<=`, `>=` work on dates.
- `===` compares the **objects**, not the moments. Compare `getTime()` instead.

```js runnable title="Which comparisons work on dates"
const a = new Date("2026-09-01T10:00:00Z");
const b = new Date("2026-09-01T10:00:00Z");
console.log(a < new Date("2026-09-02"));
console.log(a === b);
console.log(a.getTime() === b.getTime());

const dates = [new Date("2026-09-03"), new Date("2026-09-01"), new Date("2026-09-02")];
const latestFirst = dates.toSorted((x, y) => y - x);
console.log(latestFirst.map((d) => d.toISOString().slice(0, 10)).join(", "));
```

Expected output:

```text
true
false
true
2026-09-03, 2026-09-02, 2026-09-01
```

Subtracting dates gives numbers, so `(x, y) => y - x` sorts latest first.

## Dates on a Web Page

List today's orders with a time in the customer's clock. Change `ZONE` to `"America/New_York"` and run again.

```js runnable preview="status-board" title="Order times shown in the shop's time zone"
const ZONE = "Asia/Kolkata";
const orders = [
  { id: 101, placedAt: "2026-09-01T04:15:00Z" },
  { id: 102, placedAt: "2026-09-01T09:40:00Z" },
  { id: 103, placedAt: "2026-09-01T18:30:00Z" },
];
const fmt = new Intl.DateTimeFormat("en-IN", { dateStyle: "medium", timeStyle: "short", timeZone: ZONE });
const list = document.querySelector("#orders");

for (const order of orders) {
  const li = document.createElement("li");
  li.textContent = `#${order.id} — ${fmt.format(new Date(order.placedAt))}`;
  list.append(li);
}
console.log("Shown in", ZONE);
```

**Easy way to remember:** store and send in **UTC** (ISO text). Convert to the customer's clock only when you show it.

## TL;DR

- `toISOString()` for machines; `Intl.DateTimeFormat` for people.
- The locale picks the language; `timeZone` picks the clock.
- `dateStyle`/`timeStyle` cannot be mixed with single parts like `month`.
- Use half-open ranges: `>= start && < nextStart`.
- Compare moments with `getTime()`, not `===`.

## Try this

In **One moment, four wall clocks**, add `"Asia/Tokyo"` to the list. Tokyo is already on 2 September at 03:30.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Showing `toString()` to customers | It is the same everywhere | It uses each computer's zone | Different text for each person |
| `<= 30 Sep 00:00` as a month end | That includes the whole day | Use `< 1 Oct 00:00` | Late orders on the last day are lost |
| `dateA === dateB` | It compares the moments | It compares the objects | `false` for the same moment |
| `{ dateStyle, month }` together | They combine | Pick styles or single parts | `TypeError` |
| No `timeZone` for a plain date | The day is always right | Local clocks can shift the day | 31 August instead of 1 September |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `date.toISOString()` | ISO text in UTC, the same on every computer |
| `date.toString()` | long local text, different on each computer |
| `date.toDateString()` | the local date part only, different on each computer |
| `new Intl.DateTimeFormat(locale, options)` | create a formatter for people |
| `formatter.format(date)` | turn one date into text |
| `{ dateStyle: "full" }` | `"full"`, `"long"`, `"medium"`, or `"short"` date |
| `{ timeStyle: "short" }` | `"full"`, `"long"`, `"medium"`, or `"short"` time |
| `{ timeZone: "Asia/Kolkata" }` | read the moment on that zone's local clock |
| `date.getTimezoneOffset()` | minutes from local time to UTC, negative east of UTC |
| `Intl.DateTimeFormat().resolvedOptions().timeZone` | the name of this computer's zone |
| `new Date(Date.UTC(y, m + 1, 1))` | the first moment after month `m`, the end of a half-open range |
| `date >= start && date < end` | inside a half-open range |
| `a.getTime() === b.getTime()` | the same moment |

</div>

## Exercises

## What to Remember

- A date is a moment; text needs a locale and a time zone.
- Format with `Intl.DateTimeFormat`, and state the `timeZone`.
- Half-open ranges never miss the last day.

Next: **Array Fundamentals**. Keep many values in one list and change it safely.
