JavaScript Date
Learn how to create, read, modify, format, compare, calculate, validate, and work with dates and times in JavaScript using the Date object.
Introduction
Dates and times are an essential part of modern applications. Websites and applications use dates for appointments, birthdays, orders, messages, deadlines, events, subscriptions, countdowns, reports, schedules, and many other features.
JavaScript provides the built-in Date object for creating, reading, modifying, comparing, formatting, and calculating dates and times.
The Date object represents a specific moment in time. Internally, JavaScript stores that moment as the number of milliseconds that have passed since January 1, 1970 at 00:00:00 UTC.
Working with dates can initially seem confusing because months use zero-based indexes, weekdays use numeric indexes, local time differs from UTC, and date strings may be interpreted differently depending on their format.
- What the JavaScript Date object is.
- Why applications need dates and times.
- How JavaScript stores dates internally.
- What timestamps are.
- How to create the current date and time.
- How to create dates from strings.
- How to create dates from individual components.
- How to create dates from timestamps.
- How to read year, month, day, and time values.
- Why JavaScript months start from zero.
- How weekday indexes work.
- How to modify date values.
- How JavaScript automatically adjusts overflowing dates.
- How to format dates.
- How to create locale-aware date output.
- How Intl.DateTimeFormat works.
- How to work with 12-hour and 24-hour time.
- How Date.now() works.
- How Date.parse() works.
- How Date.UTC() works.
- How to compare dates.
- How to sort dates.
- How to calculate differences between dates.
- How to add and subtract days.
- How to add months and years.
- How to find the start and end of a day.
- How to calculate today, tomorrow, and yesterday.
- How to display day and month names.
- How to find the number of days in a month.
- How to detect leap years.
- How to calculate age.
- How to create countdown calculations.
- How local time and UTC differ.
- How to format dates for specific time zones.
- How to validate dates.
- How to work with HTML date inputs.
- How to work with dates received from APIs.
- How to build a complete event countdown application.
What is the Date Object?
The Date object is a built-in JavaScript object used to represent and work with a specific moment in time.
const now = new Date();
console.log(now);The exact output depends on the current date, current time, system settings, and local time zone.
DATE OBJECT
┌──────────────────────────────┐
│ Specific Moment in Time │
├──────────────────────────────┤
│ Year 2026 │
│ Month July │
│ Date 8 │
│ Day Wednesday │
│ Hours 22 │
│ Minutes 30 │
│ Seconds 00 │
│ Milliseconds 000 │
└──────────────────────────────┘
Internally Stored As:
Milliseconds Since
January 1, 1970 UTCWhy Do We Need Dates?
Applications frequently need to record when something happened, determine when something should happen, calculate time differences, and display dates in formats users can understand.
Calendars
Display days, months, appointments, holidays, and scheduled events.
Reminders
Trigger actions based on deadlines and scheduled times.
Birthdays
Store birth dates and calculate ages.
Orders
Track order creation, shipping, delivery, and return dates.
Messages
Display when messages and notifications were created.
Events
Manage event start times, end times, and countdowns.
Subscriptions
Track billing dates, renewals, and expiration dates.
Reports
Filter and group information by date ranges.
Travel
Manage departure, arrival, and booking dates.
Security
Track login times, token expiration, and session activity.
Real-World Analogy
Think of a Date object like a digital clock combined with a calendar. It represents one exact moment and allows different parts of that moment to be read or changed.
┌─────────────────────────────┐
│ CALENDAR │
├─────────────────────────────┤
│ Wednesday │
│ 8 July 2026 │
└─────────────────────────────┘
┌─────────────────────────────┐
│ CLOCK │
├─────────────────────────────┤
│ 10:30:45 PM │
└─────────────────────────────┘
│
▼
JavaScript Date
new Date()
Represents both:
Calendar Date + Clock TimeHow JavaScript Stores Dates
JavaScript internally represents a Date as a numeric timestamp. The timestamp counts milliseconds from January 1, 1970 at midnight UTC.
const date =
new Date(
'2026-07-08T12:00:00Z'
);
console.log(
date.getTime()
);The returned number represents the number of milliseconds between the Unix epoch and the specified moment.
January 1, 1970 UTC
│
│ Milliseconds
│ keep increasing
│
▼
Current or Future Date
1970 ────────────────► 2026
Timestamp
Date Object
│
▼
Numeric Milliseconds
│
▼
Formatted for DisplayUnix Timestamp
The Unix epoch is January 1, 1970 at 00:00:00 UTC. JavaScript timestamps use milliseconds, while some other systems use seconds.
const epoch = new Date(0);
console.log(epoch);- JavaScript timestamps normally use milliseconds.
- Many Unix-based systems use seconds.
- 1 second equals 1000 milliseconds.
- Always check the timestamp unit when working with APIs.
const milliseconds =
Date.now();
const seconds =
Math.floor(
milliseconds / 1000
);
console.log(milliseconds);
console.log(seconds);Creating Dates
The Date constructor supports several ways to create dates.
Current Date and Time
Calling new Date() without arguments creates a Date representing the current moment.
const now = new Date();
console.log(now);Date from String
A Date can be created from a supported date string. ISO 8601 format is generally the safest format for exchanging dates between systems.
const date =
new Date('2026-07-08');
console.log(date);const date =
new Date(
'2026-07-08T18:30:00'
);
console.log(date);const date =
new Date(
'2026-07-08T18:30:00Z'
);
console.log(
date.toISOString()
);Date from Components
A Date can be created by passing year, month index, day, hours, minutes, seconds, and milliseconds.
const date = new Date(
2026,
6,
8,
18,
30,
45,
500
);
console.log(date);- January is month 0.
- February is month 1.
- March is month 2.
- July is month 6.
- December is month 11.
Date from Timestamp
A numeric timestamp can be passed to the Date constructor.
const timestamp =
0;
const date =
new Date(timestamp);
console.log(
date.toUTCString()
);Date Constructor Syntax
1. Current Date and Time
new Date()
2. Date String
new Date(dateString)
3. Timestamp
new Date(milliseconds)
4. Individual Components
new Date(
year,
monthIndex,
day,
hours,
minutes,
seconds,
milliseconds
)
Examples:
new Date()
new Date('2026-07-08')
new Date(0)
new Date(2026, 6, 8)
new Date(
2026,
6,
8,
18,
30
)Reading Date Values
Date getter methods extract individual parts of a Date object.
getFullYear()
getFullYear() returns the four-digit year.
const date =
new Date(
2026,
6,
8
);
console.log(
date.getFullYear()
);getMonth()
getMonth() returns the month index from 0 to 11.
const date =
new Date(
2026,
6,
8
);
console.log(
date.getMonth()
);The value 6 represents July because month indexes begin at zero.
getDate()
getDate() returns the day of the month from 1 to 31.
const date =
new Date(
2026,
6,
8
);
console.log(
date.getDate()
);getDay()
getDay() returns the weekday index from 0 to 6.
const date =
new Date(
2026,
6,
8
);
console.log(
date.getDay()
);The value 3 represents Wednesday because Sunday is index 0.
getHours()
const date =
new Date(
2026,
6,
8,
18,
30
);
console.log(
date.getHours()
);getMinutes()
const date =
new Date(
2026,
6,
8,
18,
30
);
console.log(
date.getMinutes()
);getSeconds()
const date =
new Date(
2026,
6,
8,
18,
30,
45
);
console.log(
date.getSeconds()
);getMilliseconds()
const date =
new Date(
2026,
6,
8,
18,
30,
45,
500
);
console.log(
date.getMilliseconds()
);getTime()
getTime() returns the timestamp in milliseconds.
const date =
new Date(
'2026-07-08T12:00:00Z'
);
const timestamp =
date.getTime();
console.log(timestamp);Date Getter Summary
Method Returns
-----------------------------------------
getFullYear() Year
getMonth() Month Index
0 - 11
getDate() Day of Month
1 - 31
getDay() Weekday Index
0 - 6
getHours() Hours
0 - 23
getMinutes() Minutes
0 - 59
getSeconds() Seconds
0 - 59
getMilliseconds() Milliseconds
0 - 999
getTime() Timestamp
in millisecondsMonth Indexing
JavaScript months are zero-indexed when using numeric Date components and getMonth().
Month Index
----------------------
January 0
February 1
March 2
April 3
May 4
June 5
July 6
August 7
September 8
October 9
November 10
December 11const date =
new Date(
2026,
6,
8
);
const humanMonth =
date.getMonth() + 1;
console.log(humanMonth);Day Indexing
Day Index
-------------------
Sunday 0
Monday 1
Tuesday 2
Wednesday 3
Thursday 4
Friday 5
Saturday 6Modifying Dates
Date setter methods modify individual parts of an existing Date object.
setFullYear()
const date =
new Date(
2026,
6,
8
);
date.setFullYear(2030);
console.log(
date.getFullYear()
);setMonth()
const date =
new Date(
2026,
6,
8
);
date.setMonth(11);
console.log(
date.getMonth()
);setDate()
const date =
new Date(
2026,
6,
8
);
date.setDate(20);
console.log(
date.getDate()
);setHours()
const date =
new Date();
date.setHours(18);
console.log(
date.getHours()
);setMinutes()
const date =
new Date();
date.setMinutes(45);
console.log(
date.getMinutes()
);setSeconds()
const date =
new Date();
date.setSeconds(30);
console.log(
date.getSeconds()
);setMilliseconds()
const date =
new Date();
date.setMilliseconds(500);
console.log(
date.getMilliseconds()
);setTime()
setTime() replaces the Date value using a timestamp in milliseconds.
const date =
new Date();
date.setTime(0);
console.log(
date.toUTCString()
);Automatic Date Adjustment
JavaScript automatically adjusts dates when values exceed their normal ranges. This behavior is useful for date calculations.
const date =
new Date(
2026,
6,
31
);
date.setDate(
date.getDate() + 1
);
console.log(
date.toDateString()
);const date =
new Date(
2026,
7,
0
);
console.log(
date.toDateString()
);Day 0 means the final day of the previous month. This behavior is commonly used to find the number of days in a month.
Formatting Dates
A Date object can be converted into several string formats for display, storage, and data exchange.
toString()
const date =
new Date();
console.log(
date.toString()
);toDateString()
const date =
new Date(
2026,
6,
8
);
console.log(
date.toDateString()
);toTimeString()
const date =
new Date();
console.log(
date.toTimeString()
);toISOString()
toISOString() returns a standardized UTC date and time string.
const date =
new Date(
'2026-07-08T12:30:00Z'
);
console.log(
date.toISOString()
);toUTCString()
const date =
new Date(
'2026-07-08T12:30:00Z'
);
console.log(
date.toUTCString()
);toLocaleString()
toLocaleString() formats both date and time according to a locale.
const date =
new Date(
2026,
6,
8,
18,
30
);
console.log(
date.toLocaleString(
'en-IN'
)
);toLocaleDateString()
const date =
new Date(
2026,
6,
8
);
console.log(
date.toLocaleDateString(
'en-IN'
)
);toLocaleTimeString()
const date =
new Date(
2026,
6,
8,
18,
30
);
console.log(
date.toLocaleTimeString(
'en-IN'
)
);Custom Date Formatting
const date =
new Date(
2026,
6,
8
);
const day =
String(
date.getDate()
).padStart(2, '0');
const month =
String(
date.getMonth() + 1
).padStart(2, '0');
const year =
date.getFullYear();
const formatted =
`${day}-${month}-${year}`;
console.log(formatted);function formatDate(date) {
const day =
String(
date.getDate()
).padStart(2, '0');
const month =
String(
date.getMonth() + 1
).padStart(2, '0');
const year =
date.getFullYear();
return (
`${day}/${month}/${year}`
);
}
const date =
new Date(
2026,
6,
8
);
console.log(
formatDate(date)
);Intl.DateTimeFormat
Intl.DateTimeFormat provides powerful locale-aware date and time formatting.
const date =
new Date(
2026,
6,
8
);
const formatter =
new Intl.DateTimeFormat(
'en-IN',
{
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric'
}
);
console.log(
formatter.format(date)
);12-Hour and 24-Hour Time
const date =
new Date(
2026,
6,
8,
18,
30
);
console.log(
date.toLocaleTimeString(
'en-US',
{
hour: '2-digit',
minute: '2-digit',
hour12: true
}
)
);const date =
new Date(
2026,
6,
8,
18,
30
);
console.log(
date.toLocaleTimeString(
'en-GB',
{
hour: '2-digit',
minute: '2-digit',
hour12: false
}
)
);Date.now()
Date.now() returns the current timestamp in milliseconds without creating a Date object.
const timestamp =
Date.now();
console.log(timestamp);const start =
Date.now();
for (
let i = 0;
i < 1000000;
i++
) {
// Some work
}
const end =
Date.now();
console.log(
`Time: ${end - start} ms`
);Date.parse()
Date.parse() converts a supported date string into a timestamp.
const timestamp =
Date.parse(
'2026-07-08T12:00:00Z'
);
console.log(timestamp);
const date =
new Date(timestamp);
console.log(
date.toISOString()
);Date.UTC()
Date.UTC() accepts date components and returns a UTC timestamp.
const timestamp =
Date.UTC(
2026,
6,
8,
12,
30
);
const date =
new Date(timestamp);
console.log(
date.toISOString()
);Comparing Dates
Dates can be compared using their timestamps.
Date Equality
Two separate Date objects are different objects even when they represent the same moment.
const first =
new Date(
'2026-07-08'
);
const second =
new Date(
'2026-07-08'
);
console.log(
first === second
);const first =
new Date(
'2026-07-08'
);
const second =
new Date(
'2026-07-08'
);
console.log(
first.getTime()
===
second.getTime()
);Before and After
const first =
new Date(
'2026-07-08'
);
const second =
new Date(
'2026-08-01'
);
console.log(
first < second
);
console.log(
first > second
);Sorting Dates
const dates = [
new Date('2026-12-01'),
new Date('2026-01-15'),
new Date('2026-07-08')
];
dates.sort(
(a, b) => a - b
);
console.log(
dates.map(
date =>
date.toDateString()
)
);dates.sort(
(a, b) => b - a
);Date Calculations
Date calculations usually work by converting dates into timestamps and calculating the difference in milliseconds.
Difference Between Dates
const start =
new Date(
'2026-07-01'
);
const end =
new Date(
'2026-07-08'
);
const difference =
end - start;
console.log(difference);Difference in Days
const start =
new Date(
'2026-07-01T00:00:00Z'
);
const end =
new Date(
'2026-07-08T00:00:00Z'
);
const milliseconds =
end - start;
const days =
milliseconds
/
(
1000
* 60
* 60
* 24
);
console.log(days);Difference in Hours
const start =
new Date(
'2026-07-08T10:00:00Z'
);
const end =
new Date(
'2026-07-08T18:00:00Z'
);
const milliseconds =
end - start;
const hours =
milliseconds
/
(
1000
* 60
* 60
);
console.log(hours);Adding Days
const date =
new Date(
2026,
6,
8
);
date.setDate(
date.getDate() + 10
);
console.log(
date.toDateString()
);Subtracting Days
const date =
new Date(
2026,
6,
8
);
date.setDate(
date.getDate() - 10
);
console.log(
date.toDateString()
);Adding Months
const date =
new Date(
2026,
6,
8
);
date.setMonth(
date.getMonth() + 3
);
console.log(
date.toDateString()
);Adding Years
const date =
new Date(
2026,
6,
8
);
date.setFullYear(
date.getFullYear() + 5
);
console.log(
date.getFullYear()
);Start of Day
const date =
new Date();
date.setHours(
0,
0,
0,
0
);
console.log(date);End of Day
const date =
new Date();
date.setHours(
23,
59,
59,
999
);
console.log(date);Today
const today =
new Date();
today.setHours(
0,
0,
0,
0
);
console.log(today);Tomorrow
const tomorrow =
new Date();
tomorrow.setDate(
tomorrow.getDate() + 1
);
console.log(
tomorrow.toDateString()
);Yesterday
const yesterday =
new Date();
yesterday.setDate(
yesterday.getDate() - 1
);
console.log(
yesterday.toDateString()
);Day Names
const days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
const date =
new Date(
2026,
6,
8
);
const dayName =
days[date.getDay()];
console.log(dayName);Month Names
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const date =
new Date(
2026,
6,
8
);
const monthName =
months[
date.getMonth()
];
console.log(monthName);Days in a Month
The final day of a month can be found by creating the first day of the next month and using day 0.
function getDaysInMonth(
year,
monthIndex
) {
return new Date(
year,
monthIndex + 1,
0
).getDate();
}
console.log(
getDaysInMonth(
2026,
1
)
);
console.log(
getDaysInMonth(
2024,
1
)
);Leap Years
A leap year contains 366 days, with February having 29 days.
function isLeapYear(year) {
return (
year % 400 === 0
||
(
year % 4 === 0
&&
year % 100 !== 0
)
);
}
console.log(
isLeapYear(2024)
);
console.log(
isLeapYear(2026)
);Age Calculation
function calculateAge(
birthDate
) {
const today =
new Date();
let age =
today.getFullYear()
-
birthDate.getFullYear();
const monthDifference =
today.getMonth()
-
birthDate.getMonth();
if (
monthDifference < 0
||
(
monthDifference === 0
&&
today.getDate()
<
birthDate.getDate()
)
) {
age--;
}
return age;
}
const birthday =
new Date(
2000,
4,
15
);
console.log(
calculateAge(birthday)
);Countdown Calculation
function getCountdown(
targetDate
) {
const now =
new Date();
const difference =
targetDate - now;
if (difference <= 0) {
return {
days: 0,
hours: 0,
minutes: 0,
seconds: 0
};
}
const days =
Math.floor(
difference
/
(
1000
* 60
* 60
* 24
)
);
const hours =
Math.floor(
(
difference
/
(
1000
* 60
* 60
)
)
% 24
);
const minutes =
Math.floor(
(
difference
/
(
1000
* 60
)
)
% 60
);
const seconds =
Math.floor(
(
difference
/ 1000
)
% 60
);
return {
days,
hours,
minutes,
seconds
};
}
const target =
new Date(
'2027-01-01T00:00:00'
);
console.log(
getCountdown(target)
);Time Zones
A Date object represents one moment in time, but that moment can be displayed differently depending on the time zone.
Same Moment in Time
UTC
│
▼
12:00 PM UTC
│
┌───────┼────────┐
▼ ▼ ▼
Mumbai London New York
Different local clock times
Same Date Object
Different DisplayLocal Time vs UTC
Local getter methods return values in the user’s local time zone. UTC getter methods return values in Coordinated Universal Time.
const date =
new Date(
'2026-07-08T12:00:00Z'
);
console.log(
date.getHours()
);
console.log(
date.getUTCHours()
);The local hour depends on the environment’s time zone, while getUTCHours() returns 12 for this example.
UTC Getter Methods
Local Method UTC Method
------------------------------------------------
getFullYear() getUTCFullYear()
getMonth() getUTCMonth()
getDate() getUTCDate()
getDay() getUTCDay()
getHours() getUTCHours()
getMinutes() getUTCMinutes()
getSeconds() getUTCSeconds()
getMilliseconds() getUTCMilliseconds()Time Zone Formatting
const date =
new Date(
'2026-07-08T12:00:00Z'
);
const mumbai =
date.toLocaleString(
'en-IN',
{
timeZone:
'Asia/Kolkata'
}
);
const london =
date.toLocaleString(
'en-GB',
{
timeZone:
'Europe/London'
}
);
const newYork =
date.toLocaleString(
'en-US',
{
timeZone:
'America/New_York'
}
);
console.log(mumbai);
console.log(london);
console.log(newYork);Timezone Offset
getTimezoneOffset() returns the difference between UTC and local time in minutes.
const date =
new Date();
console.log(
date.getTimezoneOffset()
);- The value is expressed in minutes.
- The sign may seem reversed compared with common UTC offset notation.
- Do not manually assume a fixed offset for regions that use daylight-saving time.
Parsing Dates Safely
Ambiguous date strings should be avoided. A string such as 08/07/2026 may be interpreted differently depending on whether the expected format is DD/MM/YYYY or MM/DD/YYYY.
// ❌ Ambiguous
const first =
new Date(
'08/07/2026'
);
// ✅ Clear ISO date
const second =
new Date(
'2026-07-08'
);- Prefer ISO-style date strings.
- Know whether a string represents local time or UTC.
- Use Z when the timestamp explicitly represents UTC.
- Validate external date values before using them.
Validating Dates
An invalid Date object exists as an object but contains an invalid time value.
function isValidDate(date) {
return (
date instanceof Date
&&
!Number.isNaN(
date.getTime()
)
);
}
const valid =
new Date(
'2026-07-08'
);
const invalid =
new Date(
'not-a-date'
);
console.log(
isValidDate(valid)
);
console.log(
isValidDate(invalid)
);Invalid Date
const date =
new Date(
'hello'
);
console.log(date);
console.log(
date.getTime()
);HTML Date Inputs
HTML date and datetime-local inputs return string values. These strings should be handled carefully because date-only and local date-time values have different time-zone meanings.
<label for="eventDate">
Select Event Date
</label>
<input
type="date"
id="eventDate"
>
<button id="showDateButton">
Show Date
</button>
<p id="dateOutput"></p>const eventDate =
document.getElementById(
'eventDate'
);
const showDateButton =
document.getElementById(
'showDateButton'
);
const dateOutput =
document.getElementById(
'dateOutput'
);
showDateButton.addEventListener(
'click',
function () {
if (!eventDate.value) {
dateOutput.textContent =
'Please select a date.';
return;
}
const [
year,
month,
day
] =
eventDate.value
.split('-')
.map(Number);
const selectedDate =
new Date(
year,
month - 1,
day
);
dateOutput.textContent =
selectedDate
.toDateString();
}
);Working with APIs
APIs commonly send dates as ISO strings. The string can be converted into a Date object when date calculations or localized formatting are required.
const order = {
id: 101,
createdAt:
'2026-07-08T12:30:00.000Z'
};
const createdDate =
new Date(
order.createdAt
);
console.log(
createdDate
.toLocaleString(
'en-IN'
)
);- Store and exchange precise timestamps in a consistent format.
- ISO UTC strings are common for APIs.
- Convert strings into Date objects for calculations.
- Format dates for users at the presentation layer.
- Do not assume every user is in the same time zone.
Complete Date Example
The following example creates an event countdown application. The user selects an event date and time, and JavaScript continuously calculates the remaining days, hours, minutes, and seconds.
<div class="countdown-app">
<h2>Event Countdown</h2>
<div class="event-form">
<input
id="eventName"
type="text"
placeholder="Event name"
>
<input
id="eventDate"
type="datetime-local"
>
<button id="startButton">
Start Countdown
</button>
</div>
<div id="countdownCard">
<h3 id="eventTitle">
Select an Event
</h3>
<p id="eventDateText">
Choose a future date and time.
</p>
<div class="countdown-grid">
<div>
<strong id="days">0</strong>
<span>Days</span>
</div>
<div>
<strong id="hours">0</strong>
<span>Hours</span>
</div>
<div>
<strong id="minutes">0</strong>
<span>Minutes</span>
</div>
<div>
<strong id="seconds">0</strong>
<span>Seconds</span>
</div>
</div>
<p id="statusMessage"></p>
</div>
</div>const eventNameInput =
document.getElementById(
'eventName'
);
const eventDateInput =
document.getElementById(
'eventDate'
);
const startButton =
document.getElementById(
'startButton'
);
const eventTitle =
document.getElementById(
'eventTitle'
);
const eventDateText =
document.getElementById(
'eventDateText'
);
const daysElement =
document.getElementById(
'days'
);
const hoursElement =
document.getElementById(
'hours'
);
const minutesElement =
document.getElementById(
'minutes'
);
const secondsElement =
document.getElementById(
'seconds'
);
const statusMessage =
document.getElementById(
'statusMessage'
);
let targetDate = null;
let timerId = null;
startButton.addEventListener(
'click',
startCountdown
);
function startCountdown() {
const eventName =
eventNameInput
.value
.trim();
const eventDateValue =
eventDateInput.value;
if (
!eventName
||
!eventDateValue
) {
statusMessage.textContent =
'Enter an event name and date.';
return;
}
const selectedDate =
new Date(eventDateValue);
if (
Number.isNaN(
selectedDate.getTime()
)
) {
statusMessage.textContent =
'Please select a valid date.';
return;
}
if (
selectedDate
<=
new Date()
) {
statusMessage.textContent =
'Select a future date.';
return;
}
targetDate =
selectedDate;
eventTitle.textContent =
eventName;
eventDateText.textContent =
targetDate.toLocaleString(
'en-IN',
{
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
}
);
statusMessage.textContent =
'Countdown started.';
if (timerId !== null) {
clearInterval(timerId);
}
updateCountdown();
timerId =
setInterval(
updateCountdown,
1000
);
}
function updateCountdown() {
if (!targetDate) {
return;
}
const now =
new Date();
const difference =
targetDate - now;
if (difference <= 0) {
clearInterval(timerId);
timerId = null;
daysElement.textContent =
'0';
hoursElement.textContent =
'0';
minutesElement.textContent =
'0';
secondsElement.textContent =
'0';
statusMessage.textContent =
'🎉 The event has started!';
return;
}
const days =
Math.floor(
difference
/
(
1000
* 60
* 60
* 24
)
);
const hours =
Math.floor(
(
difference
/
(
1000
* 60
* 60
)
)
% 24
);
const minutes =
Math.floor(
(
difference
/
(
1000
* 60
)
)
% 60
);
const seconds =
Math.floor(
(
difference
/ 1000
)
% 60
);
daysElement.textContent =
days;
hoursElement.textContent =
String(hours)
.padStart(2, '0');
minutesElement.textContent =
String(minutes)
.padStart(2, '0');
secondsElement.textContent =
String(seconds)
.padStart(2, '0');
}- Reading values from HTML inputs.
- Working with datetime-local input.
- Creating Date objects from user input.
- Validating dates.
- Comparing dates.
- Rejecting past dates.
- Formatting dates for display.
- Calculating timestamp differences.
- Converting milliseconds into days.
- Converting milliseconds into hours.
- Converting milliseconds into minutes.
- Converting milliseconds into seconds.
- Using Math.floor() in time calculations.
- Using modulo to calculate remaining units.
- Using padStart() for clock-style formatting.
- Updating the DOM.
- Using setInterval() for live updates.
- Using clearInterval() when the countdown finishes.
- Managing timer state.
- Building a real-world countdown feature.
Date Processing Flow
DATE INPUT
│
▼
┌─────────────────────────────┐
│ CREATE DATE │
│ │
│ new Date() │
│ Date String │
│ Components │
│ Timestamp │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ VALIDATE │
│ │
│ getTime() │
│ Number.isNaN() │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ READ OR MODIFY │
│ │
│ Getter Methods │
│ Setter Methods │
│ Timestamp Calculations │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ PROCESS │
│ │
│ Compare │
│ Sort │
│ Add / Subtract │
│ Calculate Difference │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ FORMAT │
│ │
│ ISO │
│ Locale │
│ Custom Format │
│ Time Zone │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ OUTPUT │
│ │
│ User Interface │
│ API │
│ Storage │
│ Reports │
└─────────────────────────────┘Real-World Applications
Calendars
Display months, weekdays, appointments, and scheduled events.
Countdowns
Show remaining time before events, launches, and deadlines.
Age Calculators
Calculate ages from birth dates.
Order Tracking
Record purchase, shipping, and delivery timestamps.
Chat Applications
Display message creation and last-seen times.
Subscriptions
Manage billing cycles, renewals, and expiration dates.
Reports
Filter and group records by date ranges.
Task Managers
Track due dates, overdue tasks, and completion times.
Booking Systems
Manage departure, arrival, check-in, and reservation times.
Authentication
Track token expiration, session activity, and login timestamps.
Financial Systems
Process transaction dates, billing periods, and payment deadlines.
International Apps
Display the same moment correctly across different time zones.
Common Beginner Mistakes
- Forgetting to use new when creating a Date object.
- Confusing getDate() with getDay().
- Using getDay() when the day of the month is required.
- Using getDate() when the weekday is required.
- Forgetting that months start from zero.
- Passing 7 for July instead of 6 when using numeric components.
- Adding 1 to getMonth() and then using the result directly in setMonth().
- Assuming weekdays start from Monday.
- Forgetting that Sunday is weekday index 0.
- Comparing separate Date objects with ===.
- Expecting two equal dates to be the same object.
- Forgetting to compare timestamps for exact equality.
- Using ambiguous date strings.
- Assuming DD/MM/YYYY strings are interpreted consistently.
- Assuming MM/DD/YYYY strings are interpreted consistently everywhere.
- Ignoring the difference between local time and UTC.
- Forgetting that Z in an ISO string means UTC.
- Adding Z to a local time that should not be treated as UTC.
- Removing Z from a UTC timestamp without understanding the effect.
- Assuming toISOString() returns local time.
- Forgetting that toISOString() always represents UTC.
- Storing only formatted display strings when calculations are required.
- Performing calculations on formatted date strings.
- Forgetting that timestamps use milliseconds in JavaScript.
- Passing a timestamp in seconds directly to new Date().
- Multiplying a millisecond timestamp by 1000 unnecessarily.
- Forgetting to validate external date strings.
- Assuming an Invalid Date throws an error immediately.
- Checking only instanceof Date without checking getTime().
- Using isNaN() carelessly instead of checking the timestamp clearly.
- Mutating a Date object when an independent copy is required.
- Assigning a Date to another variable and expecting a copy.
- Forgetting that Date objects are reference values.
- Changing a Date with setter methods and unintentionally modifying shared state.
- Ignoring automatic date overflow behavior.
- Adding fixed milliseconds for calendar operations without considering daylight-saving transitions.
- Assuming every day is always exactly 24 local clock hours in all time zones.
- Manually hardcoding time-zone offsets.
- Ignoring daylight-saving time in regions that use it.
- Assuming the user and server use the same time zone.
- Formatting dates on the server and expecting identical local output for every user.
- Using locale output as a stable storage format.
- Parsing toLocaleString() output as application data.
- Using Date.parse() with non-standard ambiguous strings.
- Forgetting that datetime-local does not include a time-zone offset.
- Treating a date-only value as an exact global moment without defining the intended behavior.
- Creating birthday dates with UTC when local calendar dates are intended.
- Calculating age by dividing milliseconds by 365 days.
- Ignoring whether the birthday has occurred this year.
- Using only year subtraction for age calculation.
- Forgetting leap years.
- Assuming February always has 28 days.
- Hardcoding the number of days in every month.
- Forgetting to clear countdown intervals.
- Creating multiple intervals each time a button is clicked.
- Updating a countdown without checking whether the target date has passed.
- Allowing negative countdown values.
- Forgetting to pad single-digit clock values.
- Using innerHTML for plain date output when textContent is sufficient.
- Sending locale-formatted dates to APIs.
- Assuming database timestamps are always local time.
- Ignoring API documentation about date formats.
- Displaying raw ISO strings directly to users when a friendly format is expected.
- Converting dates repeatedly when a single Date object can be reused.
- Mixing local getter methods with UTC setter methods unintentionally.
- Mixing UTC getter methods with local setter methods unintentionally.
const date =
new Date(
2026,
6,
8
);
// ❌ Wrong: getDay() is weekday
console.log(
date.getDay()
);
// 3
// ✅ Correct: day of month
console.log(
date.getDate()
);
// 8
// ❌ Wrong: July is not 7
const wrongJuly =
new Date(
2026,
7,
8
);
// August
// ✅ Correct: July is 6
const correctJuly =
new Date(
2026,
6,
8
);
// ❌ Wrong date equality
const first =
new Date(
'2026-07-08'
);
const second =
new Date(
'2026-07-08'
);
console.log(
first === second
);
// false
// ✅ Correct date equality
console.log(
first.getTime()
===
second.getTime()
);
// true
// ❌ Ambiguous date
const ambiguous =
new Date(
'08/07/2026'
);
// ✅ Clear ISO format
const clear =
new Date(
'2026-07-08'
);Best Practices
- Use new Date() to create Date objects.
- Use ISO-style strings for data exchange.
- Avoid ambiguous date strings.
- Remember that numeric month indexes start at zero.
- Remember that getDate() returns the day of the month.
- Remember that getDay() returns the weekday index.
- Use getFullYear() instead of deprecated year methods.
- Use getTime() when an exact timestamp is required.
- Use Date.now() when only the current timestamp is needed.
- Know whether your application is working with local time or UTC.
- Use toISOString() for standardized UTC output.
- Use locale formatting for user-facing dates.
- Use Intl.DateTimeFormat for reusable locale-aware formatting.
- Specify a locale when consistent presentation is required.
- Specify a time zone when the display must target a particular region.
- Do not hardcode time-zone offsets.
- Consider daylight-saving transitions when working with international dates.
- Store precise timestamps separately from formatted display values.
- Format dates at the presentation layer.
- Validate dates received from users.
- Validate dates received from APIs.
- Check both instanceof Date and getTime() when validating Date objects.
- Use Number.isNaN(date.getTime()) to detect invalid Date values.
- Compare timestamps for exact Date equality.
- Use subtraction for chronological Date sorting.
- Create a copy before modifying a Date when the original must remain unchanged.
- Copy a Date using new Date(original.getTime()).
- Use setter methods for calendar-based adjustments.
- Understand automatic date overflow behavior.
- Use setDate() for adding or subtracting calendar days.
- Be careful when adding fixed milliseconds across daylight-saving transitions.
- Use day 0 of the next month to find the final day of a month.
- Account for leap years.
- Calculate age by checking whether the birthday has occurred this year.
- Do not calculate age by dividing milliseconds by a fixed year length.
- Use UTC consistently for globally shared timestamps when appropriate.
- Use local calendar dates for concepts such as birthdays when appropriate.
- Document the meaning of every date field in APIs.
- Document whether timestamps are UTC or local.
- Document whether date-only values represent calendar dates or exact moments.
- Use datetime-local only when local date and time input is intended.
- Do not assume datetime-local includes a time zone.
- Clear old intervals before creating new countdown intervals.
- Stop countdown timers when the target time is reached.
- Prevent negative countdown values.
- Use padStart() for clock-style output.
- Use textContent for plain date text in the DOM.
- Test dates near midnight.
- Test dates at month boundaries.
- Test dates at year boundaries.
- Test February dates.
- Test leap years.
- Test users in different time zones.
- Test invalid input.
- Test past and future dates.
- Keep date calculation logic in reusable functions.
- Use descriptive variable names such as createdAt, expiresAt, startDate, and endDate.
- Avoid mixing local and UTC methods unless the conversion is intentional.
- Use the Date object for built-in date operations and understand its limitations.
Frequently Asked Questions
What is the Date object in JavaScript?
The Date object represents a specific moment in time and provides methods for reading, modifying, comparing, and formatting dates.
How do I get the current date and time?
Use new Date() without arguments.
How does JavaScript store dates internally?
As milliseconds relative to January 1, 1970 at 00:00:00 UTC.
What is the Unix epoch?
It is January 1, 1970 at 00:00:00 UTC.
Does JavaScript use seconds or milliseconds for timestamps?
JavaScript Date timestamps normally use milliseconds.
How many milliseconds are in one second?
1000 milliseconds.
How do I create a date from a string?
Pass a supported date string to new Date().
Which date string format should I prefer?
ISO-style formats are generally the clearest for data exchange.
How do I create a date from year, month, and day?
Use new Date(year, monthIndex, day).
Why is January month 0?
JavaScript uses zero-based month indexes for numeric Date components.
What number represents December?
11.
How do I get the year?
Use getFullYear().
How do I get the month?
Use getMonth(), which returns an index from 0 to 11.
How do I get the day of the month?
Use getDate().
How do I get the weekday?
Use getDay().
What does getDay() return?
A weekday index from 0 for Sunday through 6 for Saturday.
What is the difference between getDate() and getDay()?
getDate() returns the day of the month, while getDay() returns the weekday index.
How do I get the hour?
Use getHours().
How do I get the current timestamp?
Use Date.now() or new Date().getTime().
What does getTime() return?
The Date timestamp in milliseconds.
How do I change a year?
Use setFullYear().
How do I change a month?
Use setMonth().
How do I change the day of the month?
Use setDate().
Does JavaScript automatically handle date overflow?
Yes. Values outside normal ranges automatically adjust surrounding date parts.
How do I add days to a date?
Use setDate(date.getDate() + numberOfDays).
How do I subtract days?
Use setDate(date.getDate() - numberOfDays).
How do I add months?
Use setMonth(date.getMonth() + numberOfMonths).
How do I add years?
Use setFullYear(date.getFullYear() + numberOfYears).
What does toISOString() return?
A standardized UTC date and time string.
Does toISOString() return local time?
No. It returns UTC.
What does the Z at the end of an ISO date mean?
It indicates UTC.
How do I format a date for users?
Use locale methods or Intl.DateTimeFormat.
What does toLocaleString() do?
It formats date and time according to locale settings.
What does toLocaleDateString() do?
It formats only the date portion.
What does toLocaleTimeString() do?
It formats only the time portion.
What is Intl.DateTimeFormat?
It is an internationalization API for reusable locale-aware date and time formatting.
How do I display 12-hour time?
Use locale formatting with hour12 set to true.
How do I display 24-hour time?
Use locale formatting with hour12 set to false.
What does Date.now() return?
The current timestamp in milliseconds.
What does Date.parse() return?
A timestamp parsed from a supported date string.
What does Date.UTC() return?
A UTC timestamp created from date components.
Why are two equal Date objects false with ===?
Because Date objects are compared by reference.
How do I compare two dates for exact equality?
Compare their getTime() values.
Can I use < and > with Date objects?
Yes, for chronological comparisons.
How do I sort dates?
Use a subtraction comparator such as (a, b) => a - b.
How do I calculate the difference between two dates?
Subtract one Date from another to get the difference in milliseconds.
How do I convert milliseconds to seconds?
Divide by 1000.
How do I convert milliseconds to minutes?
Divide by 1000 × 60.
How do I convert milliseconds to hours?
Divide by 1000 × 60 × 60.
How do I convert milliseconds to days?
For simple fixed-duration calculations, divide by 1000 × 60 × 60 × 24.
How do I get the start of a day?
Set hours, minutes, seconds, and milliseconds to zero.
How do I get the end of a day?
Set the time to 23:59:59.999.
How do I get tomorrow?
Create a Date and add 1 using setDate().
How do I get yesterday?
Create a Date and subtract 1 using setDate().
How do I get a day name?
Use getDay() with an array of names or use locale formatting.
How do I get a month name?
Use getMonth() with an array of names or use locale formatting.
How do I find the number of days in a month?
Create day 0 of the following month and call getDate().
What is a leap year?
A year with 366 days in which February has 29 days.
How do I calculate age correctly?
Subtract birth years and reduce the result by one if the birthday has not occurred yet this year.
Should age be calculated by dividing milliseconds by 365 days?
No. Leap years and calendar boundaries make that approach inaccurate.
What is UTC?
UTC is Coordinated Universal Time, a global time standard.
What is local time?
It is the date and time interpreted in the environment’s local time zone.
Can one Date object display different times in different locations?
Yes. The same moment can be formatted for different time zones.
How do I format a date for a specific time zone?
Use locale formatting with the timeZone option.
What does getTimezoneOffset() return?
The difference between UTC and local time in minutes.
How do I check whether a Date is valid?
Check that it is a Date and that getTime() does not return NaN.
What does an invalid Date return from getTime()?
NaN.
Does an invalid Date always throw an error?
No. Many operations simply produce Invalid Date or NaN.
What does an HTML date input return?
It returns a string in YYYY-MM-DD format when a value is selected.
What does datetime-local return?
It returns a local date and time string without an explicit time-zone offset.
How are dates commonly sent by APIs?
They are commonly sent as ISO date and time strings.
Should formatted user-facing dates be stored in a database?
Usually a precise timestamp or clearly defined date value should be stored, while user-facing formatting should happen during display.
Key Takeaways
- The Date object represents a specific moment in time.
- JavaScript stores dates internally using timestamps.
- Timestamps are measured in milliseconds.
- The Unix epoch begins on January 1, 1970 UTC.
- new Date() creates the current date and time.
- Dates can be created from strings.
- Dates can be created from numeric components.
- Dates can be created from timestamps.
- Numeric month indexes start from zero.
- getFullYear() returns the year.
- getMonth() returns a month index from 0 to 11.
- getDate() returns the day of the month.
- getDay() returns the weekday index.
- getTime() returns the timestamp.
- Setter methods modify Date objects.
- JavaScript automatically adjusts overflowing date values.
- toISOString() returns standardized UTC output.
- Locale methods format dates for users.
- Intl.DateTimeFormat provides powerful date formatting.
- Date.now() returns the current timestamp.
- Date.parse() parses supported date strings.
- Date.UTC() creates UTC timestamps from components.
- Separate Date objects are compared by reference with ===.
- Exact Date equality should compare timestamps.
- Dates can be compared chronologically.
- Dates can be sorted using subtraction.
- Subtracting Dates produces a millisecond difference.
- Days can be added using setDate().
- Months can be added using setMonth().
- Years can be added using setFullYear().
- The start of a day is 00:00:00.000.
- The end of a day is 23:59:59.999.
- Day and month names can be created using indexes or locale formatting.
- Day 0 of the next month gives the final day of the current month.
- Leap years must be considered in calendar calculations.
- Age calculations must check whether the birthday has occurred this year.
- The same moment can display differently in different time zones.
- Local methods and UTC methods are different.
- Ambiguous date strings should be avoided.
- Invalid Dates produce NaN from getTime().
- HTML date inputs return strings.
- APIs commonly exchange ISO date strings.
- Dates should be validated before important calculations.
- Date formatting should usually be separated from date storage.
Summary
The JavaScript Date object represents a specific moment in time and provides methods for creating, reading, modifying, comparing, calculating, and formatting dates.
Internally, JavaScript stores dates as timestamps measured in milliseconds relative to January 1, 1970 UTC.
Dates can be created using the current moment, date strings, timestamps, or individual date components.
Getter methods read parts of a date, while setter methods modify them. JavaScript automatically handles many overflowing date values.
Months use indexes from 0 to 11, while weekdays use indexes from 0 to 6. Understanding these indexes prevents many common Date mistakes.
Date formatting can be performed using built-in string methods, locale methods, custom formatting functions, and Intl.DateTimeFormat.
Dates should be compared using timestamps when exact equality is required. Subtracting dates provides the difference in milliseconds, which can be converted into larger time units.
Time zones are important because one exact moment can display differently in different locations. Applications should clearly distinguish between local time and UTC.
Date values from users and external systems should be validated before calculations. ISO-style formats are generally preferred for clear data exchange.
Mastering the Date object allows you to build calendars, countdowns, booking systems, age calculators, order tracking, reminders, reports, subscriptions, and many other time-based features.
- You understand the JavaScript Date object.
- You understand how JavaScript stores dates.
- You understand timestamps.
- You can create the current date and time.
- You can create dates from strings.
- You can create dates from components.
- You can create dates from timestamps.
- You can read date values.
- You understand zero-based month indexes.
- You understand weekday indexes.
- You can modify dates.
- You understand automatic date adjustment.
- You can format dates.
- You can create custom date formats.
- You can use Intl.DateTimeFormat.
- You can format 12-hour and 24-hour time.
- You can use Date.now().
- You can use Date.parse().
- You can use Date.UTC().
- You can compare dates.
- You can check exact Date equality.
- You can sort dates.
- You can calculate date differences.
- You can add and subtract days.
- You can add months and years.
- You can calculate today, tomorrow, and yesterday.
- You can display day and month names.
- You can find the number of days in a month.
- You can detect leap years.
- You can calculate age.
- You can calculate countdown values.
- You understand local time and UTC.
- You can format dates for different time zones.
- You can validate dates.
- You can detect Invalid Date values.
- You can work with HTML date inputs.
- You can work with API date strings.
- You can build a complete event countdown application.
- You are ready to learn the JavaScript Math object.