Chapter 22 of 31

JavaScript Date & Time

In many JavaScript applications, we need to work with dates and times.

For example:

  • Showing the current date and time

  • Displaying when a post was published

  • Creating countdowns

  • Checking whether a deadline has passed

  • Formatting dates for users

  • Calculating the difference between two dates

JavaScript provides the built-in Date object for handling dates and times.

Creating a Date

The easiest way to create a date representing the current moment is:

const now = new Date();

console.log(now);

The output will contain the current date and time, something similar to:

2026-08-29T06:30:00.000Z

The exact output depends on when and where the code is running.


Creating a Specific Date

We can also create a specific date.

const date = new Date("2026-08-29");

console.log(date);

We can provide a date and time as well:

const date = new Date("2026-08-29T10:30:00");

console.log(date);

Using the standard ISO-style format is generally a good choice when creating dates from strings.


Getting Date Components

JavaScript provides several methods for getting individual parts of a date.

const date = new Date();

console.log(date.getFullYear());
console.log(date.getMonth());
console.log(date.getDate());
console.log(date.getDay());

These methods return:

Method

Returns

getFullYear()

Year

getMonth()

Month

getDate()

Day of the month

getDay()

Day of the week

getHours()

Hour

getMinutes()

Minutes

getSeconds()

Seconds

getMilliseconds()

Milliseconds

Important: getMonth() Starts at 0

This is a common beginner mistake.

const date = new Date("2026-08-29");

console.log(date.getMonth());

The result is:

7

Why 7 instead of 8?

Because JavaScript counts months from 0:

0 → January
1 → February
2 → March
...
7 → August
11 → December

So if you want the normal month number:

const month = date.getMonth() + 1;

Getting the Current Time

We can get the current time components using:

const now = new Date();

console.log(now.getHours());
console.log(now.getMinutes());
console.log(now.getSeconds());

For example, the output might be:

11
45
32

This means:

11:45:32

Remember that these methods use the local time of the environment where the JavaScript code is running.


Formatting a Date

The default Date output isn't always user-friendly.

Instead of displaying the entire date object, we can create our own format:

const date = new Date();

const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();

console.log(`${day}/${month}/${year}`);

Output might be:

29/8/2026

We can also add leading zeros:

const date = new Date();

const day = String(date.getDate()).padStart(2, "0");
const month = String(date.getMonth() + 1).padStart(2, "0");
const year = date.getFullYear();

console.log(`${day}/${month}/${year}`);

Output:

29/08/2026

Converting a Date to a String

JavaScript provides several methods for converting dates into strings.

toDateString()

const date = new Date();

console.log(date.toDateString());

Example output:

Sat Aug 29 2026

toTimeString()

console.log(date.toTimeString());

This gives the time along with timezone information.

toISOString()

console.log(date.toISOString());

Example:

2026-08-29T06:30:00.000Z

ISO format is especially useful when storing or exchanging dates with servers and APIs.


Formatting Dates with toLocaleDateString()

For user-friendly formatting, toLocaleDateString() is very useful.

const date = new Date();

console.log(date.toLocaleDateString());

The exact output depends on the user's locale.

We can also specify formatting options:

const date = new Date();

console.log(
    date.toLocaleDateString("en-IN", {
        day: "2-digit",
        month: "long",
        year: "numeric"
    })
);

Example:

29 August 2026

This is much better for displaying dates in a user interface.


Setting Date and Time

JavaScript also allows us to modify parts of a date.

const date = new Date();

date.setFullYear(2030);

console.log(date);

Other useful methods include:

Method

Purpose

setFullYear()

Changes the year

setMonth()

Changes the month

setDate()

Changes the day

setHours()

Changes the hour

setMinutes()

Changes the minutes

setSeconds()

Changes the seconds

For example:

const date = new Date();

date.setDate(date.getDate() + 7);

console.log(date);

This moves the date 7 days into the future.


Comparing Dates

We can compare dates using comparison operators.

const today = new Date();
const deadline = new Date("2026-12-31");

if (today < deadline) {
    console.log("The deadline has not arrived.");
}

JavaScript internally represents dates as numeric timestamps, so comparisons like this work.


Calculating the Difference Between Dates

The .getTime() method returns the date as a timestamp measured in milliseconds since the Unix epoch.

For example:

const start = new Date("2026-08-01");
const end = new Date("2026-08-10");

const difference = end.getTime() - start.getTime();

console.log(difference);

We can convert milliseconds into days:

const days = difference / (1000 * 60 * 60 * 24);

console.log(days);

Output:

9

The calculation is:

1 second      = 1000 milliseconds
1 minute      = 60 seconds
1 hour        = 60 minutes
1 day         = 24 hours

So:

1000 × 60 × 60 × 24

gives the number of milliseconds in a day.


Unix Timestamp

A timestamp represents a point in time as a number of milliseconds from January 1, 1970 UTC.

We can get the current timestamp using:

const timestamp = Date.now();

console.log(timestamp);

The exact number changes continuously.

We can also get the timestamp of a specific date:

const date = new Date("2026-08-29");

console.log(date.getTime());

Timestamps are commonly used when storing and comparing dates in applications.


UTC Methods

JavaScript also provides UTC versions of many date methods.

For example:

const date = new Date();

console.log(date.getHours());
console.log(date.getUTCHours());

The first uses the local timezone, while the second uses UTC (Coordinated Universal Time).

Some UTC methods include:

getUTCFullYear()
getUTCMonth()
getUTCDate()
getUTCHours()
getUTCMinutes()
getUTCSeconds()

This distinction becomes important when building applications used by people in different time zones.


A Practical Example

Let's create a simple program that tells us how many days are left until a deadline.

const today = new Date();
const deadline = new Date("2026-12-31");

const difference = deadline.getTime() - today.getTime();

const daysLeft = Math.ceil(
    difference / (1000 * 60 * 60 * 24)
);

console.log(`${daysLeft} days left`);

This is the basic idea behind countdowns and deadline systems.

Conclusion

JavaScript's Date object provides the basic tools we need to work with dates and times.

Some important methods to remember are:

new Date()
getFullYear()
getMonth()
getDate()
getDay()
getHours()
getMinutes()
getSeconds()
toISOString()
toLocaleDateString()
getTime()
Date.now()

One particularly important thing to remember is that JavaScript's built-in Date API has some tricky timezone and formatting behavior. For simple date handling it's usually enough, but larger applications may use the modern Temporal API where available or a well-maintained date/time library.

For now, focus on understanding how to create dates, extract their components, format them, compare them, and calculate differences.