Skip to content

JavaScript Tutorial Dates and Time

Timestamps and Date Arithmetic in JavaScript

Lesson 91 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Under the hood, a Date is just one number: the timestamp, the milliseconds since 1 January 1970 00:00 UTC (the “Unix epoch”).

script.js
JS
const d = new Date("2026-03-15T10:30:00Z");

console.log(d.getTime());                       // → 1773570600000
console.log(new Date(1773570600000).toISOString()); // → 2026-03-15T10:30:00.000Z
console.log(typeof Date.now());                 // → number

Date.now() returns the current timestamp without creating an object. It is also the easiest way to time how long something takes.

script.js
JS
const start = Date.now();
let sum = 0;
for (let i = 0; i < 100000; i++) sum += i;
const elapsed = Date.now() - start;
console.log(elapsed >= 0); // → true

Comparing dates

Because dates convert to numbers, you can compare them with < and >. For equality, compare getTime() values (two Date objects are never === each other).

script.js
JS
const a = new Date("2026-01-01T00:00:00Z");
const b = new Date("2026-06-01T00:00:00Z");

console.log(a < b);                     // → true
console.log(a.getTime() === b.getTime()); // → false
console.log(a === new Date(a));         // → false

Difference between two dates

Subtract, then convert from milliseconds.

script.js
JS
const start = new Date("2026-03-01T00:00:00Z");
const end = new Date("2026-03-15T00:00:00Z");

const msPerDay = 24 * 60 * 60 * 1000;
console.log((end - start) / msPerDay); // → 14

Adding days, months and years

Use the setters, which handle overflow.

script.js
JS
function addDays(date, days) {
  const result = new Date(date);
  result.setUTCDate(result.getUTCDate() + days);
  return result;
}

console.log(addDays(new Date("2026-01-30T00:00:00Z"), 5).toISOString());
// → 2026-02-04T00:00:00.000Z

Adding days * 24 * 60 * 60 * 1000 milliseconds also works, but it ignores daylight saving changes in local time, where a day can have 23 or 25 hours. Setters in local time (setDate) handle those correctly.

End of the month trick

Day 0 of a month is the last day of the previous month.

script.js
JS
const lastDayOfFebruary2028 = new Date(Date.UTC(2028, 2, 0)).getUTCDate();
console.log(lastDayOfFebruary2028); // → 29

A countdown

index.html
HTML
<p id="out"></p>
<script>
  const target = Date.now() + 90 * 1000;   // 90 seconds from now
  const out = document.querySelector("#out");
  const timer = setInterval(() => {
    const left = Math.max(0, Math.round((target - Date.now()) / 1000));
    out.textContent = left + " seconds left";
    if (left === 0) clearInterval(timer);
  }, 250);
</script>