JavaScript Date Overview
The Date
object in JavaScript is used to work with dates and times. It allows you to create dates, read components like year, month, day, hours, and perform calculations.
Date objects are static. They represent a fixed moment in time. Unlike a clock, they do not automatically update as time passes
Creating Date Objects
You can create a JavaScript Date object in multiple ways.
a) Current Date and Time
Creates a Date object representing the current date and time according to your computer’s system clock.
const now = new Date();
console.log(now);
// Example: Wed Oct 08 2025 18:19:22 GMT+0530 (India Standard Time)
b) Using a Date String
- JavaScript parses the string and creates the corresponding date.
- Supported formats include
YYYY-MM-DD
,Month DD, YYYY
, or full datetime strings.
const date1 = new Date("October 13, 2014 11:13:00");
const date2 = new Date("2022-03-25");
c) Using Individual Components
- Parameters:
year, month, day, hour, minute, second, millisecond
- Months are 0-indexed:
0 = January
,11 = December
- Overflow handling: JavaScript automatically adjusts overflowed months or days:
const date = new Date(2018, 11, 24, 10, 33, 30, 0);
new Date(2018, 15, 24); // → 2019-04-24
new Date(2018, 5, 35); // → 2018-07-05
Number of Parameters | Meaning |
---|---|
2 | year, month |
3 | year, month, day |
4 | year, month, day, hour |
5 | year, month, day, hour, minute |
6 | year, month, day, hour, minute, second |
7 | year, month, day, hour, minute, second, millisecond |
One or two-digit years are treated as 19xx:
new Date(99, 11, 24); // 1999
new Date(9, 11, 24); // 1909
d) Using Milliseconds
JavaScript internally stores dates as milliseconds since January 01, 1970 00:00:00 UTC (called Unix Epoch).
- 1 day = 86,400,000 milliseconds
- This format is useful for date calculations and comparisons.
new Date(0); // 01 Jan 1970
new Date(86400000); // 01 Jan 1970 + 1 day
new Date(100000000000); // 01 Jan 1970 + 100 billion ms
new Date(-100000000000); // 01 Jan 1970 - 100 billion ms
Displaying Dates
JavaScript provides multiple ways to display dates.
Method | Description | Example Output |
---|---|---|
toString() | Default format | Wed Oct 08 2025 18:19:22 GMT+0530 |
toDateString() | Human-readable date | Wed Oct 08 2025 |
toTimeString() | Human-readable time | 18:19:22 GMT+0530 |
toUTCString() | UTC time | Wed, 08 Oct 2025 12:49:22 GMT |
toISOString() | ISO standard | 2025-10-08T12:49:22.000Z |
toLocaleDateString() | Locale-specific date | 10/08/2025 (US), 08/10/2025 (UK) |
toLocaleTimeString() | Locale-specific time | 6:19:22 PM |
Example: Using Dates
// Create a specific date
const myBirthday = new Date(1995, 11, 17); // Dec 17, 1995
// Current date
const today = new Date();
// Difference in days
const diffTime = today - myBirthday; // milliseconds
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
console.log(`You have lived ${diffDays} days.`);