Working with dates and times is a common task in JavaScript, and the Date
object provides a powerful way to handle this.
You can create a Date
object in several ways:
const now = new Date();
console.log(now); // Outputs current date and time, e.g. 2025-06-23T14:30:00.000Z
const specificDate = new Date('2025-12-25T10:00:00');
console.log(specificDate); // Dec 25, 2025, 10:00 AM
const customDate = new Date(2025, 11, 25, 10, 0, 0);
// Note: Month is zero-based, so 11 = December
console.log(customDate);
JavaScript provides several built-in methods to convert Date objects into readable strings:
toLocaleDateString()
Formats the date according to the local conventions:console.log(now.toLocaleDateString()); // e.g. "6/23/2025" in US locale
console.log(now.toLocaleDateString('en-GB')); // "23/06/2025" for UK
toISOString()
Returns the date in ISO 8601 format — great for APIs:console.log(now.toISOString()); // "2025-06-23T14:30:00.000Z"
You can also extract specific parts of the date and build your own format:
.getFullYear()
— Year (e.g., 2025).getMonth()
— Month (0–11, so add 1 for human-readable).getDate()
— Day of the month.getHours()
, .getMinutes()
, .getSeconds()
— Time partsExample:
const year = now.getFullYear();
const month = now.getMonth() + 1; // Add 1 because months start at 0
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const formatted = `${day}/${month}/${year} ${hours}:${minutes}`;
console.log(formatted); // e.g. "23/6/2025 14:30"
const currentDate = new Date();
console.log('Locale date:', currentDate.toLocaleDateString());
console.log('ISO string:', currentDate.toISOString());
console.log('Custom format:', `${currentDate.getDate()}/${currentDate.getMonth() + 1}/${currentDate.getFullYear()}`);
This outputs the current date in multiple human- and machine-friendly formats, helping you display or process dates in the way your application needs.
Mastering date creation and formatting unlocks powerful capabilities for handling time-based data in JavaScript!
When working with dates and times in JavaScript, understanding timestamps and how to calculate differences between dates is crucial for many applications — such as measuring elapsed time, creating countdowns, or even calculating someone's age.
A timestamp is a way of representing a specific moment in time as a single number. In JavaScript, timestamps are expressed as the number of milliseconds that have passed since the Unix epoch, which is January 1, 1970, 00:00:00 UTC. This format allows for precise time calculations and comparisons.
You can get the current timestamp using:
Date.now()
— returns the number of milliseconds since the Unix epoch for the current moment.dateObject.getTime()
— returns the timestamp for a specific Date
object.// Using Date.now()
const nowTimestamp = Date.now();
console.log(nowTimestamp); // e.g., 1687551937264
// Using getTime() on a Date object
const now = new Date();
const timestampFromDate = now.getTime();
console.log(timestampFromDate); // Should be the same as Date.now()
To find the difference between two dates, you subtract their timestamps. The result is the difference in milliseconds, which you can then convert to seconds, minutes, hours, or days.
const date1 = new Date('2025-07-01');
const date2 = new Date('2025-07-10');
const diffInMs = date2.getTime() - date1.getTime(); // Difference in milliseconds
const millisecondsPerDay = 1000 * 60 * 60 * 24; // 86,400,000 ms in a day
const diffInDays = diffInMs / millisecondsPerDay;
console.log(`Days between: ${diffInDays}`); // Outputs: Days between: 9
Suppose you want to measure how long a task takes in your program:
const startTime = Date.now();
// Simulate some process with a delay
setTimeout(() => {
const endTime = Date.now();
const elapsedTimeMs = endTime - startTime;
console.log(`Elapsed time: ${elapsedTimeMs} milliseconds`);
}, 2000);
This code measures the time elapsed during a 2-second delay.
You can calculate the remaining time until a future event by subtracting the current timestamp from the event’s timestamp.
const futureDate = new Date('2025-12-31T23:59:59');
const now = Date.now();
const timeLeftMs = futureDate.getTime() - now;
if (timeLeftMs > 0) {
const secondsLeft = Math.floor(timeLeftMs / 1000);
console.log(`Countdown: ${secondsLeft} seconds left`);
} else {
console.log("The event has already occurred!");
}
You can calculate someone's age by comparing their birthdate to the current date:
function calculateAge(birthDateStr) {
const birthDate = new Date(birthDateStr);
const now = new Date();
const diffInMs = now.getTime() - birthDate.getTime();
const millisecondsPerYear = 1000 * 60 * 60 * 24 * 365.25; // Approximate, accounts for leap years
return Math.floor(diffInMs / millisecondsPerYear);
}
const age = calculateAge('1990-06-23');
console.log(`Age: ${age} years`);
Date.now()
or getTime()
to get timestamps.Mastering timestamps and date differences opens up many possibilities for handling time in JavaScript!
setTimeout
, setInterval
JavaScript provides two essential timer functions — setTimeout
and setInterval
— that allow you to schedule code execution after a delay or repeatedly at intervals. These are incredibly useful for creating dynamic behaviors like delayed messages, animations, countdowns, and polling.
setTimeout
: Delayed ExecutionsetTimeout
schedules a function to run once after a specified number of milliseconds.
const timeoutId = setTimeout(functionToRun, delayInMilliseconds);
functionToRun
: The callback function to execute.delayInMilliseconds
: How long to wait before running the function.setTimeout(() => {
console.log("This message appears after 3 seconds.");
}, 3000);
After 3 seconds, the message will appear in the console.
If you need to cancel a scheduled timeout before it runs, save its ID and call clearTimeout()
:
const timeoutId = setTimeout(() => {
console.log("You won't see this message.");
}, 5000);
// Cancel the timeout before it runs
clearTimeout(timeoutId);
setInterval
: Repeated ExecutionsetInterval
runs a function repeatedly at fixed intervals (in milliseconds) until stopped.
const intervalId = setInterval(functionToRun, intervalInMilliseconds);
functionToRun
: The callback function to execute repeatedly.intervalInMilliseconds
: How often to run the function.let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count >= 5) {
clearInterval(intervalId); // Stop after 5 counts
console.log("Counter stopped.");
}
}, 1000);
This code increments and logs the counter every second. After reaching 5, it stops the interval.
Use clearInterval()
with the interval ID to stop repeated execution:
clearInterval(intervalId);
Avoid overlapping intervals: If your interval callback takes longer than the interval duration, callbacks can pile up, causing unexpected behavior. To prevent this, you can:
setTimeout
recursively instead of setInterval
when the callback involves asynchronous or longer tasks.Always clear timers: To prevent memory leaks or unwanted behavior, clear timeouts and intervals when they are no longer needed (e.g., when a component unmounts in frameworks or when the user navigates away).
Use meaningful variable names: Naming your timeout or interval IDs clearly (messageTimeout
, counterInterval
) helps keep your code readable.
// Show a greeting after 2 seconds
const greetingTimeout = setTimeout(() => {
console.log("Hello! Welcome to our site.");
}, 2000);
// Every 3 seconds, remind the user to check notifications
let reminderCount = 0;
const reminderInterval = setInterval(() => {
reminderCount++;
console.log("Don't forget to check your notifications!");
if (reminderCount === 3) {
clearInterval(reminderInterval);
console.log("Reminder stopped after 3 times.");
}
}, 3000);
Function | Purpose | Cancel with |
---|---|---|
setTimeout |
Run code once after a delay | clearTimeout() |
setInterval |
Run code repeatedly at intervals | clearInterval() |
Timers are simple yet powerful tools to control timing in your JavaScript programs. Use them wisely to create smooth user experiences, animations, and automated tasks!