How to Calculate Date Differences

May 28, 20267 min read

Why Date Differences Matter

Calculating the time between two dates comes up constantly — project deadlines, age verification, subscription billing, and legal compliance all depend on precise date math. Getting it wrong can cause billing errors or regulatory violations.

The Challenge with Months

Days are fixed units, but months vary from 28 to 31 days. This makes "1 month ago" ambiguous without context. February 28 minus one month could reasonably be January 28 or January 31, depending on the convention.

Common Approaches

ApproachHow It WorksBest For
Day countCount total days between datesShort durations, deadlines
Calendar monthsIncrement/decrement months, adjust daysAge, billing, contracts
30-day monthAssume 30 days per monthFinancial calculations

Calculating Age from Date of Birth

Age calculation requires calendar-month logic, not simple division:

  1. Subtract birth year from current year
  2. If the current month-day is before the birth month-day, subtract 1
  3. Handle February 29 births in non-leap years
function calculateAge(birthDate, referenceDate = new Date()) {
  let years = referenceDate.getFullYear() - birthDate.getFullYear()
  let months = referenceDate.getMonth() - birthDate.getMonth()
  let days = referenceDate.getDate() - birthDate.getDate()

  if (days < 0) {
    months--
    const prevMonth = new Date(referenceDate.getFullYear(), referenceDate.getMonth(), 0)
    days += prevMonth.getDate()
  }

  if (months < 0) {
    years--
    months += 12
  }

  return { years, months, days }
}

Computing Days Between Two Dates

For simple day counts, use the difference in milliseconds:

const daysBetween = (start, end) =>
  Math.floor((end - start) / (1000 * 60 * 60 * 24))

This works reliably because JavaScript Date subtraction returns milliseconds. Always use Math.floor to avoid fractional days from time components.

Business Days Calculation

Excluding weekends requires iterating through the date range:

function businessDaysBetween(start, end) {
  let count = 0
  const current = new Date(start)
  while (current <= end) {
    const day = current.getDay()
    if (day !== 0 && day !== 6) count++
    current.setDate(current.getDate() + 1)
  }
  return count
}

For production use, also subtract public holidays by maintaining a holiday calendar.

Edge Cases to Watch

  • Timezone differences: Dates created as new Date("2024-01-01") are UTC, while new Date(2024, 0, 1) is local. Mixing them causes off-by-one errors.
  • Daylight saving time: A day is not always 24 hours near DST transitions. Use date-only arithmetic, not hour-based math.
  • Leap seconds: Standard JavaScript does not handle leap seconds. For most applications, this is irrelevant.

Try It Yourself

Use the Age Calculator to compute exact age in years, months, and days with all edge cases handled automatically.