Unix timestamp conversion
Unix timestamps count elapsed time since 1970-01-01T00:00:00Z.
APIs commonly use seconds, while JavaScript Date expects milliseconds.
const seconds = 1712345678
const date = new Date(seconds * 1000)
const milliseconds = Date.now()
const unixSeconds = Math.floor(milliseconds / 1000)
A 10 digit value is usually seconds. A 13 digit value is usually milliseconds.
Verify both with a Unix timestamp converter.
Adding and subtracting dates
Calendar arithmetic needs clear rules for month ends, leap years, daylight saving
changes, and local vs UTC behavior.
function addDays(date, days) {
const result = new Date(date)
result.setDate(result.getDate() + days)
return result
}
For one-off checks, use the
date add/subtract calculator.
Days between dates
Decide whether the end date is included before implementing a range calculation.
Most APIs use an exclusive end date.
function diffUtcDays(a, b) {
const start = Date.UTC(a.getUTCFullYear(), a.getUTCMonth(), a.getUTCDate())
const end = Date.UTC(b.getUTCFullYear(), b.getUTCMonth(), b.getUTCDate())
return Math.round((end - start) / 86400000)
}
Compare calendar days, weeks, approximate months, and business days with a
days between dates calculator.
ISO week numbers
ISO weeks start on Monday. Week 1 is the week containing the first Thursday of the
calendar year, and the ISO week year can differ from the calendar year.
function isoWeek(date) {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
const day = d.getUTCDay() || 7
d.setUTCDate(d.getUTCDate() + 4 - day)
const year = d.getUTCFullYear()
const start = new Date(Date.UTC(year, 0, 1))
const week = Math.ceil(((d - start) / 86400000 + 1) / 7)
return { year, week }
}
Check any date with the
ISO week number calculator
or see the current week number.
Age calculation
Human age is usually based on completed calendar years, months, and days, not a
millisecond duration divided by an average year length.
function ageInYears(dateOfBirth, onDate = new Date()) {
let age = onDate.getFullYear() - dateOfBirth.getFullYear()
const birthday = new Date(onDate.getFullYear(), dateOfBirth.getMonth(), dateOfBirth.getDate())
if (onDate < birthday) age -= 1
return age
}
Verify leap years and comparison dates with an
exact age calculator.
Testing date code
Good tests cover boundaries: start of day, end of month, leap day, daylight saving
changes, ISO week crossovers, and seconds vs milliseconds.
| Case |
Example |
| Leap day |
2024-02-29 |
| ISO crossover |
2021-01-01 |
| Month end add |
2026-01-31 + 1 month |