# Date Fundamentals

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

> What a Date stores, the current time and timestamps, four ways to create a date, reading parts with local and UTC getters, the zero-based month, rollover, invalid dates, parsing ISO strings, validation, date arithmetic and the setters.

## What Is a Date in JavaScript?

**Date** = an object that stores one moment in time.

- Inside, it is **one number**: milliseconds since 1 January 1970 (UTC).
- **Timestamp** = that number.
- Year, month, day and hour are all worked out from it.

**Simple lesson:** a date is a number underneath. Adding a day means making the number bigger.

### A Real-World Example

An order is placed on 1 September and delivery takes 3 days.
The shop adds 3 days to the order date to show **Arrives 4 September**.
The same code must also handle 30 September + 3 days = 3 October.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="A timeline from 1970 to now. A marker slides along it. Underneath, the same moment is shown as a timestamp number and as a calendar date." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <line x1="40" y1="60" x2="520" y2="60" stroke="#94a3b8" strokeWidth="3" />
    <text x="40" y="45" fontSize="12" fill="#475569">1 Jan 1970 = 0</text>
    <text x="520" y="45" textAnchor="end" fontSize="12" fill="#475569">1 Sep 2026</text>
    <circle r="9" cy="60" fill="#2563eb">
      <animate attributeName="cx" values="40;520;520" keyTimes="0;0.7;1" dur="4s" repeatCount="indefinite" />
    </circle>
    <rect x="60" y="95" width="200" height="44" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="160" y="122" textAnchor="middle" fontSize="13" fontFamily="monospace" fill="#1e40af">1788264000000</text>
    <rect x="300" y="95" width="200" height="44" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="400" y="122" textAnchor="middle" fontSize="13" fill="#166534">1 Sep 2026, 12:00 UTC</text>
    <text x="280" y="122" textAnchor="middle" fontSize="16" fill="#475569">=</text>
  </svg>
  <figcaption>One number of milliseconds, read as a calendar date.</figcaption>
</figure>

In these boxes, "now" is frozen at **1 September 2026, 12:00 UTC**, so every answer matches the text. Some boxes fail on purpose; their titles say so.

## What You Will Learn

1. What a date stores, and how to make one.
2. How to read its parts, in local time and in UTC.
3. The month rule (months start at 0) and rollover.
4. How to parse and validate dates.
5. How to add, subtract and change dates.

## Date basics

### What a date is

```js runnable title="A date is one number underneath"
const placed = new Date("2026-09-01T12:00:00Z");
console.log(placed.getTime());
console.log(placed.toISOString());
```

Expected output:

```text
1788264000000
2026-09-01T12:00:00.000Z
```

### Current date and time

`new Date()` with nothing inside means **now**.

```js runnable title="new Date() with no arguments is now"
const now = new Date();
console.log(now.toISOString());
```

Expected output:

```text
2026-09-01T12:00:00.000Z
```

### Getting the timestamp

`Date.now()` gives the number straight away. `getTime()` reads it from a date.

```js runnable title="Two ways to get a timestamp"
console.log(Date.now());
console.log(new Date().getTime());
```

Expected output:

```text
1788264000000
1788264000000
```

### One number, many views

```js runnable title="The same moment, read five ways"
const d = new Date("2026-09-01T12:00:00Z");
console.log(d.getTime());
console.log(d.toISOString());
console.log(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
console.log(d.getUTCHours());
console.log(d.toISOString().slice(0, 10));
```

Expected output:

```text
1788264000000
2026-09-01T12:00:00.000Z
2026 8 1
12
2026-09-01
```

The month says `8` for September. More on that below.

## Creating dates

| Way | Example |
|---|---|
| Now | `new Date()` |
| From text | `new Date("2026-09-01")` |
| From parts | `new Date(Date.UTC(2026, 8, 1))` |
| From a timestamp | `new Date(1788264000000)` |

### `new Date()`

Passing another date makes a **copy**. Change the copy, and the original stays safe.

```js runnable title="No arguments means now, a date argument means a copy"
const original = new Date("2026-09-01T00:00:00Z");
const copy = new Date(original);
copy.setUTCDate(10);
console.log(original.toISOString().slice(0, 10));
console.log(copy.toISOString().slice(0, 10));
```

Expected output:

```text
2026-09-01
2026-09-10
```

### Date from a string

Use the **ISO** format: `YYYY-MM-DD`, or `YYYY-MM-DDTHH:mm:ssZ`. The `Z` means UTC.

```js runnable title="Two ISO strings, one with a time and one without"
console.log(new Date("2026-09-01").toISOString());
console.log(new Date("2026-09-01T18:30:00Z").toISOString());
```

Expected output:

```text
2026-09-01T00:00:00.000Z
2026-09-01T18:30:00.000Z
```

### Date from parts

- `new Date(y, m, d)` reads the parts in **your computer's** time zone.
- `new Date(Date.UTC(y, m, d))` reads them in **UTC**. Same answer everywhere.

```js runnable title="The same parts, read as local time and as UTC"
const utc = new Date(Date.UTC(2026, 8, 1, 9, 30));
console.log(utc.toISOString());
```

Expected output:

```text
2026-09-01T09:30:00.000Z
```

### Date from a timestamp

```js runnable title="Numbers in, dates out"
console.log(new Date(0).toISOString());
console.log(new Date(1788264000000).toISOString());
```

Expected output:

```text
1970-01-01T00:00:00.000Z
2026-09-01T12:00:00.000Z
```

## Reading date parts

### Getting year, month, day

```js runnable title="The calendar parts of one moment"
const d = new Date("2026-12-25T10:15:30Z");
console.log(d.getUTCFullYear());
console.log(d.getUTCMonth());
console.log(d.getUTCDate());
console.log(d.getUTCDay());
```

Expected output:

```text
2026
11
25
5
```

- `getUTCMonth()` 11 = December (0-based).
- `getUTCDay()` = day of the week: 0 is Sunday, so 5 is Friday.

### Getting hours, minutes, seconds

`getUTCHours()`, `getUTCMinutes()` and `getUTCSeconds()` read the clock; `getUTCMilliseconds()` reads the thousandths.

```js runnable title="The clock parts of one moment"
const d = new Date("2026-12-25T10:15:30Z");
console.log(d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
```

Expected output:

```text
10 15 30
```

### Local getters

`getFullYear()`, `getMonth()`, `getDate()`, `getDay()`, `getHours()` and `getMinutes()` use **your computer's** time zone. In India the same moment reads 15:45.

```js runnable title="Local getters answer in this computer's time zone"
const d = new Date("2026-12-25T10:15:30Z");
console.log("Local hour here:", d.getHours());
```

### UTC getters

`getUTCHours()` and friends give the same answer on every computer. Use them in shared code.

```js runnable title="UTC getters answer the same way everywhere"
const d = new Date("2026-12-25T20:00:00Z");
console.log("UTC:", d.getUTCDate(), d.getUTCHours());
```

Expected output:

```text
UTC: 25 20
```

## Month and day rules

### Months start from 0

January is `0` and December is `11`. Days of the month still start at `1`.

```js runnable title="Month 8 is September, and month 9 is October"
console.log(new Date(Date.UTC(2026, 8, 1)).toISOString().slice(0, 10));
console.log(new Date(Date.UTC(2026, 9, 1)).toISOString().slice(0, 10));
```

Expected output:

```text
2026-09-01
2026-10-01
```

### Days do not start from 0

Day `1` is the first of the month. Day `0` means "the day before the 1st", the last day of last month.

```js runnable title="Day 1 is the first of the month, day 0 is the last day of the month before"
console.log(new Date(Date.UTC(2026, 8, 1)).toISOString().slice(0, 10));
console.log(new Date(Date.UTC(2026, 8, 0)).toISOString().slice(0, 10));
```

Expected output:

```text
2026-09-01
2026-08-31
```

### Rollover behaviour

Out-of-range parts **roll over** into the next month or year. No error.

```js runnable title="Out-of-range parts roll into the next month or year"
console.log(new Date(Date.UTC(2026, 8, 33)).toISOString().slice(0, 10));
console.log(new Date(Date.UTC(2026, 12, 1)).toISOString().slice(0, 10));
```

Expected output:

```text
2026-10-03
2027-01-01
```

### Invalid Date

Text that is not a date gives an **Invalid Date**. Its timestamp is `NaN`.

```js runnable title="Text that is not a date gives an invalid date"
const bad = new Date("next Tuesday");
console.log(bad.getTime());
console.log(String(bad));
```

Expected output:

```text
NaN
Invalid Date
```

Some methods throw on an invalid date:

```js runnable expect-error title="toISOString() refuses an invalid date"
new Date("soon").toISOString();
```

## Parsing dates

### ISO date strings

Only ISO text is read the same way in every browser. Avoid formats like `"01/09/2026"`: is that 1 September or 9 January?

```js runnable title="Only the ISO formats are guaranteed to parse the same everywhere"
console.log(new Date("2026-09-01T10:00:00Z").toISOString());
console.log(new Date("2026-09-01T10:00:00+05:30").toISOString());
```

Expected output:

```text
2026-09-01T10:00:00.000Z
2026-09-01T04:30:00.000Z
```

### Local time vs UTC time

- Date only (`"2026-09-01"`) is read as **UTC**.
- Date and time with no `Z` (`"2026-09-01T00:00:00"`) is read as **local** time.

```js runnable title="Two strings that look alike and are read differently"
const a = new Date("2026-09-01");
const b = new Date("2026-09-01T00:00:00");
console.log(a.toISOString());
console.log("Same moment here?", a.getTime() === b.getTime());
```

On a computer in India, the second one is 5½ hours earlier in UTC. Add `Z` when you mean UTC.

## Date validation

### Checking whether a date is valid

A date is valid when its timestamp is not `NaN`.

```js runnable title="A function that returns a date, or null when the text is not a date"
function parseDate(text) {
  const d = new Date(text);
  return Number.isNaN(d.getTime()) ? null : d;
}
console.log(parseDate("2026-09-01")?.toISOString());
console.log(parseDate("tomorrow"));
```

Expected output:

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

Rollover hides typos like 31 February. Check that the parts come back the same:

```js runnable title="A stricter check that catches 31 February"
function isRealDay(y, m, d) {
  const date = new Date(Date.UTC(y, m - 1, d));
  return date.getUTCMonth() === m - 1 && date.getUTCDate() === d;
}
console.log(isRealDay(2026, 2, 28));
console.log(isRealDay(2026, 2, 31));
```

Expected output:

```text
true
false
```

## Date arithmetic

### Subtracting dates

`b - a` gives the difference in **milliseconds**.

```js runnable title="Two dates, one difference in milliseconds"
const DAY = 24 * 60 * 60 * 1000;
const ordered = new Date("2026-09-01T12:00:00Z");
const delivered = new Date("2026-09-04T12:00:00Z");
console.log(delivered - ordered);
console.log((delivered - ordered) / DAY, "days");
```

Expected output:

```text
259200000
3 days
```

### Adding days

Change the day part on a **copy**. Rollover handles month ends for you.

```js runnable title="Adding and subtracting whole days"
function addDays(date, days) {
  const copy = new Date(date);
  copy.setUTCDate(copy.getUTCDate() + days);
  return copy;
}
const placed = new Date("2026-09-29T00:00:00Z");
console.log(addDays(placed, 3).toISOString().slice(0, 10));
console.log(addDays(placed, -30).toISOString().slice(0, 10));
```

Expected output:

```text
2026-10-02
2026-08-30
```

### Adding months

Adding a month to 31 January rolls past February:

```js runnable title="Adding one month, and what happens after 31 January"
const a = new Date("2026-03-15T00:00:00Z");
a.setUTCMonth(a.getUTCMonth() + 1);
const b = new Date("2026-01-31T00:00:00Z");
b.setUTCMonth(b.getUTCMonth() + 1);
console.log(a.toISOString().slice(0, 10));
console.log(b.toISOString().slice(0, 10));
```

Expected output:

```text
2026-04-15
2026-03-03
```

### Adding years

29 February only exists in leap years, so it rolls to 1 March:

```js runnable title="Adding one year to an ordinary day and to a leap day"
const ordinary = new Date("2026-09-01T00:00:00Z");
ordinary.setUTCFullYear(2027);
const leap = new Date("2028-02-29T00:00:00Z");
leap.setUTCFullYear(2029);
console.log(ordinary.toISOString().slice(0, 10));
console.log(leap.toISOString().slice(0, 10));
```

Expected output:

```text
2027-09-01
2029-03-01
```

### Calculating date differences

For whole calendar days, compare the **start** of each day, then round.

```js runnable title="Calendar days between two moments, and days until a deadline"
const DAY = 24 * 60 * 60 * 1000;
const startOfDay = (d) => Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
const saleEnds = new Date("2026-09-10T08:00:00Z");
const daysLeft = Math.round((startOfDay(saleEnds) - startOfDay(new Date())) / DAY);
console.log("Sale ends in", daysLeft, "days");
```

Expected output:

```text
Sale ends in 9 days
```

## Changing dates

`set...` methods **change the date itself**. Copy first if you need the original.

### `setDate()`

```js runnable title="Setting the day, and adding days through rollover"
const d = new Date("2026-09-01T00:00:00Z");
d.setUTCDate(15);
console.log(d.toISOString().slice(0, 10));
d.setUTCDate(d.getUTCDate() + 20);
console.log(d.toISOString().slice(0, 10));
```

Expected output:

```text
2026-09-15
2026-10-05
```

### `setFullYear()`

`setUTCFullYear(y, m, d)` can set the year, month and day together.

```js runnable title="Changing the year, then the year, month and day together"
const d = new Date("2026-09-01T00:00:00Z");
d.setUTCFullYear(2027);
console.log(d.toISOString().slice(0, 10));
d.setUTCFullYear(2028, 0, 15);
console.log(d.toISOString().slice(0, 10));
```

Expected output:

```text
2027-09-01
2028-01-15
```

### `setMonth()`

```js runnable title="Moving a date to another month"
const d = new Date("2026-09-01T00:00:00Z");
d.setUTCMonth(11);
console.log(d.toISOString().slice(0, 10));
```

Expected output:

```text
2026-12-01
```

### `setHours()`

`setUTCHours(0, 0, 0, 0)` moves a date to the start of its day.

```js runnable title="Setting a time of day, and moving to the start of the day"
const d = new Date("2026-09-01T15:45:10Z");
d.setUTCHours(9, 30);
console.log(d.toISOString());
d.setUTCHours(0, 0, 0, 0);
console.log(d.toISOString());
```

Expected output:

```text
2026-09-01T09:30:10.000Z
2026-09-01T00:00:00.000Z
```

## Dates on a Web Page

A date input gives text like `"2026-09-01"`. Turn it into a date, add the delivery days on a copy, and show the result. Try 29 September + 3 days.

```js runnable preview="delivery-date" title="A delivery date checker"
const ordered = document.querySelector("#ordered");
const days = document.querySelector("#days");
const arrives = document.querySelector("#arrives");

function addDays(date, count) {
  const copy = new Date(date);
  copy.setUTCDate(copy.getUTCDate() + count);
  return copy;
}

document.querySelector("#check").addEventListener("click", () => {
  const start = new Date(ordered.value);
  if (Number.isNaN(start.getTime())) {
    arrives.textContent = "Please pick a valid date.";
    return;
  }
  const end = addDays(start, Number(days.value));
  arrives.textContent = `Arrives on ${end.toISOString().slice(0, 10)}`;
  console.log(ordered.value, "+", days.value, "days =", end.toISOString().slice(0, 10));
});
```

**Easy way to remember:** months are like array positions (start at 0). Days are like calendar pages (start at 1).

## TL;DR

- A date is one number: milliseconds since 1970 in UTC.
- Use ISO text, or `Date.UTC(y, m, d)`, for dates that read the same everywhere.
- Months start at 0. Parts that are too big roll over.
- Invalid dates have a `NaN` timestamp. Check with `Number.isNaN(d.getTime())`.
- `set...` changes the date. Copy first, and subtract dates for milliseconds.

## Try this

Create `new Date(Date.UTC(2026, 1, 29))`. 2026 has no 29 February, so it rolls over to 1 March. Rollover never throws an error.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `Date.UTC(2026, 9, 1)` for September | Months start at 1 | Months start at 0 | You get October |
| `date.setUTCDate(...)` on a shared date | `set` makes a copy | `set` changes the date itself | The original date changes |
| `"01/09/2026"` | Every browser reads it the same | Only ISO text is safe | 1 Sep or 9 Jan, by browser |
| `"2026-09-01T00:00"` with no `Z` | It is UTC | It is local time | Off by hours, sometimes a day |
| Not checking `NaN` | Bad text throws | It gives an Invalid Date | `NaN` spreads into totals |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `new Date()` | the current moment |
| `Date.now()` | the current timestamp, as a number |
| `new Date("2026-07-09T10:52:00Z")` | a date from an ISO string in UTC |
| `new Date(Date.UTC(2026, 6, 9))` | a date from parts in UTC, where month `6` is July |
| `new Date(2026, 6, 9)` | a date from parts in local time |
| `new Date(1783594320000)` | a date from a timestamp |
| `new Date(date)` | a copy of another date |
| `date.getTime()` | the stored timestamp |
| `date.getUTCFullYear()`, `getUTCMonth()`, `getUTCDate()` | year, month from `0`, day of the month from `1` |
| `date.getUTCHours()`, `getUTCMinutes()`, `getUTCSeconds()` | the clock parts in UTC |
| `date.getFullYear()`, `getHours()`, … | the same parts in local time |
| `Number.isNaN(date.getTime())` | `true` for an invalid date |
| `later - earlier` | the difference in milliseconds |
| `copy.setUTCDate(copy.getUTCDate() + n)` | add `n` calendar days |
| `copy.setUTCMonth(copy.getUTCMonth() + n)` | add `n` months |
| `copy.setUTCHours(0, 0, 0, 0)` | move to the start of the day |

</div>

## Exercises

## What to Remember

- A date is a number underneath.
- Months are 0-based; rollover is automatic.
- Copy before you change, and use UTC methods for shared answers.

Next: **Date Formatting and Time Zones**. Show dates in a way people can read, in any time zone.
