In JavaScript, you can use Date
object to work with dates and times.
Note:
- JavaScript months are 0-indexed, i.e., January = 0, February = 1, ..., December = 11.
- The
Date
object shows a specific moment in time by counting how many milliseconds have passed since January 1, 1970 (UTC time).
Creating Date Objects
JavaScript provides the following ways to create Date
objects.
Current Date and Time
You can use new Date()
to create a Date
object with current date and time.
const now = new Date();
console.log(now); // Current date and time
This gives you the exact date and time when the code runs.
Creating Dates from Strings
You can pass a date string to new Date()
:
const date1 = new Date("2024-12-25"); // Just the date
const date2 = new Date("2024-12-25T10:30:00"); // With time
const date3 = new Date("2024-12-25T10:30:00.000Z"); // UTC time
The ISO 8601 format (YYYY-MM-DD
) is the safest and most consistent for creating dates from strings.
JavaScript also supports other formats, but they depend on the browser’s locale. So they might not behave the same everywhere.
const date4 = new Date("December 25, 2024");
const date5 = new Date("Dec 25, 2024 10:30:00");
const date6 = new Date("25 Dec 2024");
Creating Dates from Components
You can also create a date by giving each part, like year, month, day, hour, etc.
Syntax:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
Example:
const date1 = new Date(2024, 11, 25); // December 25, 2024
const date2 = new Date(2024, 11, 25, 10, 30); // With hour and minute
const date3 = new Date(2024, 11, 25, 10, 30, 45); // With seconds
const date4 = new Date(2024, 11, 25, 10, 30, 45, 500); // With milliseconds
Note: JavaScript months are 0-indexed, i.e., January = 0, February = 1, ..., December = 11.
Creating Dates from Timestamps
Every JavaScript Date is stored internally as a timestamp, the number of milliseconds that have passed since January 1, 1970, at 00:00:00 UTC. This is called the Unix Epoch.
const timestamp = 1735128600000;
const date = new Date(timestamp);
Here, 1735128600000
means 1,735,128,600,000 milliseconds since Jan 1, 1970. When you pass that number to new Date()
, JavaScript translates it into a human-readable date.
If you want the current timestamp, then you can use Date.now()
:
const timestamp = Date.now();
console.log(timestamp);
// To turn that timestamp into a Date object:
const now = new Date(timestamp);
console.log(now);
Getting Date Components
JavaScript provides the following ways to extract specific date components, like year, month, day, or time.
Getting Year
const date = new Date("2024-12-25T15:30:45");
console.log(date.getFullYear()); // Output: 2024
Getting Month
const date = new Date("2024-12-25T15:30:45");
console.log(date.getMonth()); // Output: 11 (December)
Getting Date
const date = new Date("2024-12-25T15:30:45");
console.log(date.getDate()); // Output: 25
Getting Day
const date = new Date("2024-12-25T15:30:45");
console.log(date.getDay()); // Output: 3 Day of week (0=Sunday, 1=Monday, etc.)
Getting Hours
const date = new Date("2024-12-25T15:30:45.123");
console.log(date.getHours()); // Output: 15
Getting Minutes
const date = new Date("2024-12-25T15:30:45.123");
console.log(date.getMinutes()); // Output: 30
Getting Seconds
const date = new Date("2024-12-25T15:30:45.123");
console.log(date.getSeconds()); // Output: 45
Getting Milliseconds
const date = new Date("2024-12-25T15:30:45.123");
console.log(date.getMilliseconds()); // Output: 123
Getting Timestamp
const date = new Date("2024-12-25T15:30:45");
console.log(date.getTime()); // Milliseconds since epoch
console.log(Date.now()); // Current timestamp
console.log(+date); // Shorthand for getTime()
Setting Date Components
JavaScript provides the following ways to update or set specific date components, like year, month, day, or time.
Setting Individual Components
Setting Year
const date = new Date();
date.setFullYear(2024);
Setting Month
const date = new Date();
date.setMonth(11);
Setting Date
const date = new Date();
date.setDate(25);
Setting Hours
const date = new Date();
date.setHours(15);
Setting Minutes
const date = new Date();
date.setMinutes(30);
Setting Seconds
const date = new Date();
date.setSeconds(45);
Setting Milliseconds
const date = new Date();
date.setMilliseconds(123);
Combining all of the above:
const date = new Date();
// Set date parts
date.setFullYear(2024);
date.setMonth(11);
date.setDate(25);
// Set time parts
date.setHours(15);
date.setMinutes(30);
date.setSeconds(45);
date.setMilliseconds(123);
console.log(date); // Output: Wed Dec 25 2024 15:30:45 GMT+0530 (India Standard Time)
Setting Multiple Components
Some setter methods allows you to update multiple values together in one line.
const date = new Date();
// Set year, month, and day together
date.setFullYear(2024, 11, 25); // December 25, 2024
// Set hours, minutes, seconds, and milliseconds
date.setHours(15, 30, 45, 123); // 3:30:45.123 PM
console.log(date); // Output: Wed Dec 25 2024 15:30:45 GMT+0530 (India Standard Time)
Setting from Timestamp
You can also set a Date to a specific moment using a timestamp (milliseconds since Jan 1, 1970).
const date = new Date();
date.setTime(1735128600000); // Sets it to a specific point in time
console.log(date); // Output: Wed Dec 25 2024 17:40:00 GMT+0530 (India Standard Time)
Formatting Dates
JavaScript provides you several ways to format a date into a readable string.
Built-in Formatting Methods
Full Date and Time String:
const date = new Date("2024-12-25T15:30:45");
console.log(date.toString()); // Output: Wed Dec 25 2024 15:30:45 GMT+0530 (India Standard Time)
Date Only:
const date = new Date("2024-12-25T15:30:45");
console.log(date.toDateString()); // Output: Wed Dec 25 2024
Time Only:
const date = new Date("2024-12-25T15:30:45");
console.log(date.toTimeString()); // Output: 15:30:45 GMT+0530 (India Standard Time)
ISO Format:
const date = new Date("2024-12-25T15:30:45");
console.log(date.toISOString()); // Output: 2024-12-25T10:00:45.000Z
JSON Representation:
const date = new Date("2024-12-25T15:30:45");
console.log(date.toJSON()); // Output: 2024-12-25T10:00:45.000Z (Same as toISOString())
Locale-specific Formatting
JavaScript provides you the following ways to format a date according to region or language.
const date = new Date("2024-12-25T15:30:45");
// Default locale (based on your browser)
console.log(date.toLocaleDateString()); // Output: 12/25/2024
console.log(date.toLocaleTimeString()); // Output: 3:30:45 PM
console.log(date.toLocaleString()); // Output: 12/25/2024, 3:30:45 PM
// Specific locales
console.log(date.toLocaleDateString("en-GB")); // Output: 25/12/2024 (UK format)
console.log(date.toLocaleDateString("de-DE")); // Output: 25.12.2024 (German format)
console.log(date.toLocaleDateString("ja-JP")); // Output: 2024/12/25 (Japanese format)
Custom Formatting with Options
You can also customize exactly how the date/time looks using options objects.
Common option properties and their possible values:
Option property | Description | Possible values | Example output |
---|---|---|---|
year |
Format the year | "numeric" , "2-digit" |
2024 , 24 |
month |
Format the month | "numeric" , "2-digit" , "long" , "short" , "narrow" |
12 , 12 (but padded when needed), December , Dec , D |
day |
Format the day of the month | "numeric" , "2-digit" |
5 , 05 |
weekday |
Show the day of the week | "long" , "short" , "narrow" |
Wednesday , Wed , W |
hour |
Format the hour | "numeric" , "2-digit" |
3 , 03 |
minute |
Format the minutes | "numeric" , "2-digit" |
7 , 07 |
second |
Format the seconds | "numeric" , "2-digit" |
9 , 09 |
timeZoneName |
Show the timezone name | "short" , "long" |
GMT+5:30 , India Standard Time |
hour12 |
Use 12-hour clock (AM/PM) or 24-hour clock | true (12-hour), false (24-hour) |
3:00 PM (true), 15:00 (false) |
Date Formatting Options
const date = new Date("2024-12-25T15:30:45");
const dateOptions = {
year: "numeric",
month: "long",
day: "numeric",
weekday: "long",
};
console.log(date.toLocaleDateString("en-US", dateOptions)); // Output: Wednesday, December 25, 2024
Time Formatting Options
const date = new Date("2024-12-25T15:30:45");
const timeOptions = {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: true,
};
console.log(date.toLocaleTimeString("en-US", timeOptions)); // Output: 03:30:45 PM
Combined Formatting Options
const date = new Date("2024-12-25T15:30:45");
const combinedOptions = {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
timeZoneName: "short",
};
console.log(date.toLocaleString("en-US", combinedOptions)); // Output: Dec 25, 2024, 03:30 PM GMT+5:30
Custom Formatting Function
You can also build your own formatter if you want full control over your date format. This is great when you want the same format across browsers and platforms.
function formatDate(date, format = "YYYY-MM-DD") {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
const hours = String(d.getHours()).padStart(2, "0");
const minutes = String(d.getMinutes()).padStart(2, "0");
const seconds = String(d.getSeconds()).padStart(2, "0");
const formats = {
"YYYY-MM-DD": `${year}-${month}-${day}`,
"MM/DD/YYYY": `${month}/${day}/${year}`,
"DD/MM/YYYY": `${day}/${month}/${year}`,
"YYYY-MM-DD HH:mm:ss": `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
"MM/DD/YYYY HH:mm": `${month}/${day}/${year} ${hours}:${minutes}`,
};
return formats[format] || d.toLocaleDateString();
}
console.log(formatDate("2024-12-25T15:30:45", "MM/DD/YYYY")); // Output: 12/25/2024
console.log(formatDate("2024-12-25T15:30:45", "DD/MM/YYYY")); // Output: 25/12/2024
Here,
function formatDate(date, format = "YYYY-MM-DD") {
defines a function named formatDate. It takes two parameters:date
: a date string or object.format
: the desired format. If not provided, it defaults to "YYYY-MM-DD".
const d = new Date(date);
creates a realDate
object from the input, which you provide (date).const year = d.getFullYear();
extracts year.const month = String(d.getMonth() + 1).padStart(2, "0");
extracts month and adds a leading zero if needed (e.g., "5" becomes "05") usingpadStart(2, "0")
and then converts it to a string.const day = String(d.getDate()).padStart(2, "0");
extracts date and adds a leading zero if needed usingpadStart(2, "0")
and then converts it to a string.const hours = String(d.getHours()).padStart(2, "0");
extracts hours and adds a leading zero if needed usingpadStart(2, "0")
and then converts it to a string.const minutes = String(d.getMinutes()).padStart(2, "0");
extracts minutes and adds a leading zero if needed usingpadStart(2, "0")
and then converts it to a string.const seconds = String(d.getSeconds()).padStart(2, "0");
extracts seconds and adds a leading zero if needed usingpadStart(2, "0")
and then converts it to a string.const formats = {...};
is an object that holds different date formats as key-value pairs:- The key is the format name (what the user passed in).
- The value is a string with the formatted output.
return formats[format] || d.toLocaleDateString();
returns the correct format from the formats object. If the format isn't found, it falls back to a basic default usingtoLocaleDateString()
.
Date Arithmetic and Comparisons
In JavaScript, you can do much more than just display dates, you can compare them, calculate time differences, and even add or subtract days, hours, or minutes.
Comparing Dates
JavaScript lets you compare dates using regular comparison operators like <
, >
, and ===
.
const date1 = new Date("2024-12-25");
const date2 = new Date("2024-12-30");
const date3 = new Date("2024-12-25");
console.log(date1 < date2); // Output: true
console.log(date1 > date2); // Output: false
console.log(date1 <= date3); // Output: true
console.log(date1 == date3); // Output: false (Even if the date values are the same, the objects are different.)
// Always compare timestamps instead:
console.log(date1.getTime() === date3.getTime()); // Output: true (same timestamp)
Date Arithmetic (Time Differences)
You can subtract one date from another to get the difference in milliseconds:
const date1 = new Date("2024-12-25");
const date2 = new Date("2024-12-30");
// Difference in milliseconds
const diffMs = date2 - date1;
console.log(diffMs); // Output: 432000000
// Now convert it to days or other units
const diffSeconds = diffMs / 1000; // 1 second = 1000 ms
const diffMinutes = diffMs / (1000 * 60); // 1 minute = 60 seconds
const diffHours = diffMs / (1000 * 60 * 60); // 1 hour = 60 minutes
const diffDays = diffMs / (1000 * 60 * 60 * 24); // 1 day = 24 hours
console.log(`${diffSeconds} seconds`); // Output: 432000 seconds
console.log(`${diffMinutes} minutes`); // Output: 7200 minutes
console.log(`${diffHours} hours`); // Output: 120 hours
console.log(`${diffDays} days`); // Output: 5 days
Adding or Subtracting Time
You can add or subtract days/hours by changing the timestamp:
const date = new Date("2024-12-25T15:30:45");
// Add 7 days
const futureDate = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000);
console.log(futureDate);
// Subtract 3 days
const pastDate = new Date(date.getTime() - 3 * 24 * 60 * 60 * 1000);
console.log(pastDate);
// Add 2 hours
const laterTime = new Date(date.getTime() + 2 * 60 * 60 * 1000);
console.log(laterTime);
Here,
date.getTime()
gives the timestamp in milliseconds.7 * 24 * 60 * 60 * 1000
= milliseconds in 7 days.- You add that to the original timestamp and create a new Date from it.
3 * 24 * 60 * 60 * 1000
= milliseconds in 3 days.2 * 60 * 60 * 1000
= milliseconds in 2 hours.
Working with Timezones
JavaScript Date objects are based on UTC (Coordinated Universal Time) internally, but you can display time in your local timezone.
Local vs UTC Time
const date = new Date("2024-12-25T15:30:45");
// Local time components
console.log("Local:", {
year: date.getFullYear(),
month: date.getMonth(),
date: date.getDate(),
hours: date.getHours(),
});
// UTC time components
console.log("UTC:", {
year: date.getUTCFullYear(),
month: date.getUTCMonth(),
date: date.getUTCDate(),
hours: date.getUTCHours(),
});
Here,
getFullYear()
,getMonth()
, etc. → return values based on your local timegetUTCFullYear()
,getUTCMonth()
, etc. → return values based on UTC- This is useful when working with servers or APIs that store time in UTC but you want to display it locally.
Timezone Information
const date = new Date();
// Getting timezone offset in minutes
const offsetMinutes = date.getTimezoneOffset();
console.log(`UTC offset: ${offsetMinutes} minutes`); // Output: UTC offset: -330 minutes
Note: Your outputs can differ based on your locale.
getTimezoneOffset()
returns how many minutes behind or ahead your local time is from UTC.
You can convert it to hours:
const offsetHours = offsetMinutes / 60;
console.log(`UTC offset: ${offsetHours} hours`); // Output: UTC offset: -5.5 hours
You can also find out the timezone name:
const timezoneName = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(`Timezone: ${timezoneName}`); // Output: Timezone: Asia/Kolkata
This gives a readable name like "Asia/Kolkata" or "America/New_York".
UTC String Formatting
const date = new Date("2024-12-25T15:30:45");
console.log(date.toUTCString()); // Output: "Wed, 25 Dec 2024 20:30:45 GMT"
console.log(date.toISOString()); // Output: "2024-12-25T20:30:45.000Z"
Both show the same UTC time, just in different formats. toUTCString()
is human-readable and toISOString()
is perfect for APIs and databases.
Note: The time becomes 20:30:45 in UTC because 15:30 IST = 10:00 UTC.
Creating UTC Dates
When you create a date using JavaScript, it’s usually based on your local timezone. But sometimes, you need to create a date that's exactly in UTC, for example, when working with servers or databases.
You can do it by using Date.UTC()
.
Using Date.UTC()
:
// Create a date in UTC
const utcDate = new Date(Date.UTC(2024, 11, 25, 15, 30, 45));
console.log(utcDate.toISOString()); // Output: "2024-12-25T15:30:45.000Z"
Here,
Date.UTC(year, month, day, hours, minutes, seconds)
returns a timestamp (in milliseconds) for that exact moment in UTC.- Then you pass that timestamp into
new Date()
to create a realDate
object. - Month is 0-indexed (11 = December).
- Time is not converted to local, it's stored exactly as UTC.
Comparing with local time:
// Compare with local date
const localDate = new Date(2024, 11, 25, 15, 30, 45);
console.log(localDate.toISOString());
Here,
- You created the date without using
Date.UTC()
. new Date(2024, 11, 25, 15, 30, 45)
assumes the time is in your local timezone.- When you call
.toISOString()
, JavaScript converts that local time to UTC. - So if you're in India (UTC+5:30), it will output
2024-12-25T10:00:45.000Z
.
Practical Examples
Age Calculator
This function calculates your age in years based on your date of birth. It considers today’s date and adjusts the age if your birthday hasn’t come yet this year.
function calculateAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
const monthDiff = today.getMonth() - birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
age--;
}
return age;
}
console.log(calculateAge("1990-05-15"));
Here,
today
gets the current date and time (e.g. July 10, 2025).birth
converts the passedbirthDate
string into a realDate
object.age
gets the difference in years between now and your birth year.- But this is just a rough estimate, it doesn’t account for whether your birthday has happened yet this year. For example:
- If you were born in May 1990, and today is July 2025, age is 2025 - 1990 = 35
- If today is March 2025, and your birthday is in May, you’re still 34
- So you need to check that.
const monthDiff = today.getMonth() - birth.getMonth();
checks if your birthday month has already passed.if (...) { age--; }
, if your birth month is later than the current month or it's your birth month, but the day hasn't come yet, then you're still younger by 1 year. So you subtract 1.console.log(calculateAge("1990-05-15"));
- If today is July 10, 2025 → Output: 35
- But if today were April 1, 2025, you'd still be 34, because May 15 hasn't come yet.
Date Range Checker
This function tells you whether a given date is between two other dates.
function isDateInRange(date, startDate, endDate) {
const checkDate = new Date(date);
const start = new Date(startDate);
const end = new Date(endDate);
return checkDate >= start && checkDate <= end;
}
console.log(isDateInRange("2024-12-25", "2024-12-01", "2024-12-31")); // Output: true
Here,
- This function takes three parameters: a date to check, a start date and an end date.
checkDate
,start
, andend
converts all the input strings into realDate
objects so you can compare them numerically.return checkDate >= start && checkDate <= end;
compares:checkDate >= start
: is the date on or after the start?checkDate <= end
: is it on or before the end?
console.log(...)
December 25 is between December 1 and December 31 so it returns true.
Best Practices for Working with Dates
Performance Considerations
Use Date.now()
for timestamps:
Date.now()
is cleaner and faster when you just need the current timestamp.
const timestamp1 = Date.now(); // Preferred (faster)
const timestamp2 = new Date().getTime(); // Slower
Cache date objects:
If you're using the same date multiple times, don’t recreate it. Creating new Date()
inside every comparison or operation slows things down, especially in loops.
function processDateRange(startDate, endDate) {
const start = new Date(startDate); // Create once
const end = new Date(endDate); // Create once
// Use cached objects for multiple operations
const diffMs = end - start;
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
return {
start: start.toLocaleDateString(),
end: end.toLocaleDateString(),
days: diffDays,
};
}
Avoid creating new Date objects in loops:
Move new Date(startDate)
and new Date(endDate)
outside the loop. Only parse new dates when necessary.
function findDatesInRange(dates, startDate, endDate) {
const start = new Date(startDate);
const end = new Date(endDate);
return dates.filter((dateStr) => {
const date = new Date(dateStr);
return date >= start && date <= end;
});
}
Error Handling with Dates
Dates created from invalid input can silently fail. That’s why you should validate them.
Safe Date parsing:
function safeParseDate(dateInput) {
try {
const date = new Date(dateInput);
if (isNaN(date.getTime())) {
throw new Error("Invalid date");
}
return { success: true, date };
} catch (error) {
return { success: false, error: error.message };
}
}
console.log(safeParseDate("2024-12-25")); // Output: {success: true, date: Date}
Here,
isNaN(date.getTime())
checks if the date is invalid.- This returns a safe object with either a date or an error.
Format Dates safely:
function formatDate(date, format = "YYYY-MM-DD") {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
const hours = String(d.getHours()).padStart(2, "0");
const minutes = String(d.getMinutes()).padStart(2, "0");
const seconds = String(d.getSeconds()).padStart(2, "0");
const formats = {
"YYYY-MM-DD": `${year}-${month}-${day}`,
"MM/DD/YYYY": `${month}/${day}/${year}`,
"DD/MM/YYYY": `${day}/${month}/${year}`,
"YYYY-MM-DD HH:mm:ss": `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
"MM/DD/YYYY HH:mm": `${month}/${day}/${year} ${hours}:${minutes}`,
};
return formats[format] || d.toLocaleDateString();
}
function formatDateSafely(dateInput, format = "YYYY-MM-DD") {
const parseResult = safeParseDate(dateInput);
if (!parseResult.success) {
return `Invalid date: ${parseResult.error}`;
}
return formatDate(parseResult.date, format);
}
console.log(safeParseDate("invalid")); // Output: {success: false, error: 'Invalid date'}
Here,
- First checks if the date is valid.
- Then formats it
formatDate()
function.