When working with time in vanilla JavaScript, the core tool youβll be using is the Date object.
A particularly useful method is .getTime(), which returns the number of milliseconds that have passed since January 1, 1970 (UTC), also known as the Unix epoch.
Because time is measured in milliseconds, itβs important to understand the basic conversions. A second is equivalent to 1000 milliseconds, a minute to 60 seconds, a hour to 60 minutes, and a day to 24 hours. Once you know this, you can calculate durations easily using simple math.
Example: D-Day Countdown in JavaScript
Letβs build a simple D-Day countdown timer. This script calculates the difference between the current time and a target date, then updates the countdown every second.
const text = document.querySelector("h1");
function getTime() {
const targetDate = new Date("2026-01-01T00:00:00+0900");
const currentDate = new Date();
const diffInMs = targetDate.getTime() - currentDate.getTime();
const totalSeconds = Math.floor(diffInMs / 1000);
const totalMinutes = Math.floor(totalSeconds / 60);
const totalHours = Math.floor(totalMinutes / 60);
const totalDays = Math.floor(totalHours / 24);
const seconds = totalSeconds % 60;
const minutes = totalMinutes % 60;
const hours = totalHours % 24;
text.innerHTML = `${totalDays} days ${hours} hours ${minutes} minutes ${seconds} seconds`;
}
function init() {
setInterval(getTime, 1000); // Update every second
}
init();This is a simple but effective pattern for building real-time countdowns without any external libraries.