Calculate the duration between two dates.

← Date, Time, and Duration · Ref: Q1174

Subtract one date from another using the - operator:

  dur <- endDate - startDate
  stdout.println(dur)

Date subtraction produces a Duration. Use component accessors like .days(), .hours() to extract parts. Negative durations occur when subtracting a later date from an earlier one. See Q539 for date difference details. See Q540 for adding time.

Example

defines module qa.datetime.durationbetween

  defines program

    DurationBetweenDemo()
      stdout <- Stdout()

      // Subtract two dates to get a Duration
      startDate <- 2024-01-01
      endDate <- 2024-12-31
      dur <- endDate - startDate
      stdout.println(`Duration: ${dur}`)
      stdout.println(`Days: ${dur.days()}`)

      // Time subtraction
      startTime <- 09:00
      endTime <- 17:30
      workDay <- endTime - startTime
      stdout.println(`Work day: ${workDay}`)
      stdout.println(`Hours: ${workDay.hours()}`)

      // Duration literal comparison
      oneWeek <- P7D
      twoWeeks <- P14D
      stdout.println(`One week < two weeks: ${oneWeek < twoWeeks}`)

      // Negative duration
      backwards <- startDate - endDate
      stdout.println(`Backwards: ${backwards}`)

Common mistakes

E50060 — Date has no daysBetween() method. Use the - operator to subtract dates and get a Duration, then call .days() for the day count. See ek9 -h E50060 for details.

Incorrect:

dur <- endDate.daysBetween(startDate)

Correct:

dur <- endDate - startDate
Other ways to ask this
  • Write code to find the time span between a start and end date
  • I have two dates and need the duration between them
  • Given a start date and end date, compute how much time has elapsed
  • In Java I'd use ChronoUnit.DAYS.between(). Write the EK9 equivalent

Coming from another language?

Java: ChronoUnit.DAYS.between(d1, d2) or Period.between(). Python: (date2 - date1).days. Rust: chrono signed_duration_since(). Go: t2.Sub(t1). EK9: endDate - startDate gives Duration directly.

Keywords: duration, subtract, days, between, elapsed, difference, date, time span