Limited Offer
60% OFF on all plans!

Date & Time in Node.js

Complete guide to JavaScript Date & Time: creating dates, timestamps, parsing, formatting, comparison, arithmetic, timezones, UTC vs local time, and common backend use cases.

Introduction to Date & Time

JavaScript represents date and time using the built-in Date object. Internally, it stores time as milliseconds since the Unix Epoch (1 Jan 1970 UTC).

1. What is a Date in JavaScript?

Date is a built-in object.

Creating Date Objects

JavaScript provides multiple ways to create Date objects depending on the input.

1. Current Date & Time

Create date for the current moment.

2. Date from Timestamp

Use milliseconds since epoch.

3. Date from Components

Year, month, day, hour, minute.

4. Date from String

Parse ISO and date strings.

Timestamps

Timestamps are commonly used in databases, logs, and APIs.

1. Getting Current Timestamp

Milliseconds since epoch.

2. Date to Timestamp

Convert Date to milliseconds.

Getting Date Components

Date provides methods to extract year, month, day, and time.

1. Local Date Components

Get values in local time.

2. UTC Date Components

Get values in UTC.

Formatting Dates

Formatting is required for logs, APIs, and user-facing output.

1. toString & toISOString

Convert date to string.

2. toLocaleString

Locale-aware formatting.

Comparing Dates

Dates can be compared using timestamps.

1. Comparing Two Dates

Use timestamps or operators.

Date Arithmetic

Date arithmetic is commonly used for expiry, scheduling, and TTL.

1. Adding / Subtracting Days

Modify timestamps.

2. Difference Between Two Dates

Calculate time difference.

Timezones & UTC

Timezones are one of the most common sources of bugs in backend systems.

1. Local Time vs UTC

Difference between local and UTC.

Best Practices

Handling date and time correctly is critical in backend systems.

1. Recommended Practices

Rules to follow.