Last updated
Date Arithmetic
Date calculations involve adding or subtracting time intervals, finding the
difference between two dates, and determining day-of-week or week-of-year.
JavaScript's Date object handles most date arithmetic, but
libraries like date-fns and Temporal (the new
standard API) provide more reliable and readable date operations.
Common Date Calculations
JavaScript
// Days between two dates
function daysBetween(date1, date2) {
const ms = Math.abs(new Date(date2) - new Date(date1));
return Math.floor(ms / (1000 * 60 * 60 * 24));
}
// Add days to a date
function addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Add months (handles month-end correctly)
function addMonths(date, months) {
const result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
}
// Get age from birthdate
function getAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
const m = today.getMonth() - birth.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--;
return age;
}
console.log(daysBetween('2026-01-01', '2026-03-22')); // 80
console.log(getAge('1990-06-15')); // 35
Date Format Reference
| Format | Example | Standard |
|---|---|---|
| ISO 8601 | 2026-03-22T14:30:00Z | International |
| US format | 03/22/2026 | MM/DD/YYYY |
| EU format | 22/03/2026 | DD/MM/YYYY |
| Unix timestamp | 1742601600 | Seconds since epoch |
| RFC 2822 | Sun, 22 Mar 2026 14:30:00 +0000 | Email headers |