Swift example

How to calculate the difference between two dates in Swift

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Ask a Calendar: calendar.dateComponents([.day], from: start, to: end).day! gives whole days, and [.year, .month, .day, .hour, .minute] gives a breakdown. For the exact gap in seconds, use end.timeIntervalSince(start). To add a day, write calendar.date(byAdding: .day, value: 1, to: date), not addingTimeInterval(86400), which drifts by an hour across a daylight saving change.

A Date in Swift is a single instant, stored as seconds since a reference date. It has no year, month or time zone of its own, so there are two kinds of difference. The exact elapsed time is a number of seconds, and Date gives it to you directly. Days, months and years depend on a calendar and a time zone, so you ask a Calendar. The sections below cover both, adding days and months to a date, what changes across a daylight saving switch, and turning a count of seconds into hours, minutes and seconds, then a table to pick from. All of these need import Foundation, except the plain arithmetic in the last section. Each example runs on this page: hit Run, then edit the code and run it again.

1Calendar.dateComponents: years, months, days and hoursRecommended

dateComponents(_:from:to:) takes a set of units and returns a DateComponents value with one field per unit. Ask for several units and you get a breakdown, where each unit holds what is left after the larger ones. Ask for one unit and you get the total in that unit. Fields are optional Ints: the units you asked for are filled in and the rest are nil. The example builds its own calendar with a fixed time zone; Calendar.current follows the device, so the same two dates can give a different count of days on a phone in another zone.

date_components.swift
import Foundation

// A Gregorian calendar in UTC, so the result does not depend on the device
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "UTC")!

let start = calendar.date(from: DateComponents(
    year: 2024, month: 1, day: 15, hour: 9, minute: 30))!
let end = calendar.date(from: DateComponents(
    year: 2026, month: 3, day: 2, hour: 17, minute: 45, second: 10))!

// A breakdown: each unit holds what is left after the larger ones
let parts = calendar.dateComponents(
    [.year, .month, .day, .hour, .minute, .second], from: start, to: end)
print("\(parts.year!)y \(parts.month!)m \(parts.day!)d",
      "\(parts.hour!)h \(parts.minute!)min \(parts.second!)s")

// Ask for one unit to get the total in that unit
let days = calendar.dateComponents([.day], from: start, to: end).day!
let months = calendar.dateComponents([.month], from: start, to: end).month!
let hours = calendar.dateComponents([.hour], from: start, to: end).hour!
print("total days:", days)
print("total months:", months)
print("total hours:", hours)

// Swap the dates and the result is negative
let back = calendar.dateComponents([.day], from: end, to: start).day!
print("end to start:", back)

// Units you did not ask for are nil
let dayHour = calendar.dateComponents([.day, .hour], from: start, to: end)
print(dayHour.day!, dayHour.hour!, dayHour.minute as Any)

Output

January 15, 2024 at 9:30 to March 2, 2026 at 17:45:10 breaks down to 2y 1m 15d 8h 15min 10s. Asked one unit at a time, the same gap is 777 days, 25 months or 18656 hours. Counts are whole units, rounded toward zero: the extra 8 hours don't make day 778. Swapping from and to gives -777, and asking for [.day, .hour] leaves minute as nil. The ! after each field is safe because you asked for that unit; see how to unwrap an optional for the other cases.

2timeIntervalSince: the exact gap in seconds

end.timeIntervalSince(start) returns a TimeInterval, which is a typealias for Double holding seconds. It needs no calendar or time zone, because it measures the time that actually passed between two instants. Divide by 60 or 3,600 for minutes or hours, and convert with Int(…) when you want whole units. The result is positive when end is later and negative when it is earlier; dates also compare directly with <, > and ==. The example reads the dates from ISO 8601 strings, which carry their own offset (the Z means UTC).

time_interval.swift
import Foundation

// ISO 8601 strings carry their own offset, so the instants are exact
let iso = ISO8601DateFormatter()
let start = iso.date(from: "2026-05-04T08:15:00Z")!
let end = iso.date(from: "2026-05-06T10:45:30Z")!

// TimeInterval is a Double holding seconds
let seconds = end.timeIntervalSince(start)
print(type(of: seconds), seconds)

print("minutes:", seconds / 60)
print("hours:", seconds / 3600)
print("whole hours:", Int(seconds / 3600))

// The sign tells you the order; abs gives the distance
let backwards = start.timeIntervalSince(end)
print("backwards:", backwards, "distance:", abs(backwards))

// Dates compare directly
print(start < end, start == end)

// Two decimals for display
print(String(format: "%.2f hours", seconds / 3600))

Output

type(of:) prints Double, since TimeInterval is only another name for it. The gap is 181830.0 seconds, which is 3030.5 minutes or 50.50833333333333 hours. Int(seconds / 3600) cuts that to 50 (it truncates, it doesn't round), and String(format:) rounds it to 50.51 hours for display. Reversed, the interval is -181830.0. Use this when you want elapsed time; when you want calendar days or months, use dateComponents, because a day isn't always 86,400 seconds (section 4).

3Add days, months or years to a date

calendar.date(byAdding: .day, value: 1, to: date) adds one calendar day. A negative value goes back. It returns an optional Date, which is nil only when the result can't be built, so a ! is common for plain Gregorian arithmetic. Months and years don't have a fixed length: when the same day doesn't exist in the target month, the calendar uses that month's last day instead of spilling into the next one. To add several units at once, pass a DateComponents value.

add_days.swift
import Foundation

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "UTC")!

let iso = ISO8601DateFormatter()
let start = iso.date(from: "2026-01-31T10:00:00Z")!

// date(byAdding:value:to:) returns Date? (nil only if it cannot be built)
let tomorrow = calendar.date(byAdding: .day, value: 1, to: start)!
let yesterday = calendar.date(byAdding: .day, value: -1, to: start)!
print("tomorrow: ", iso.string(from: tomorrow))
print("yesterday:", iso.string(from: yesterday))

// Months clamp to the last valid day instead of spilling over
let nextMonth = calendar.date(byAdding: .month, value: 1, to: start)!
let twoMonths = calendar.date(byAdding: .month, value: 2, to: start)!
print("+1 month: ", iso.string(from: nextMonth))
print("+2 months:", iso.string(from: twoMonths))

// Several units at once with DateComponents
let later = calendar.date(
    byAdding: DateComponents(month: 1, day: 10, hour: 6), to: start)!
print("+1m 10d 6h:", iso.string(from: later))

// Leap day plus one year
let leapDay = iso.date(from: "2024-02-29T00:00:00Z")!
let nextYear = calendar.date(byAdding: .year, value: 1, to: leapDay)!
print("leap +1y: ", iso.string(from: nextYear))

// Seconds-based arithmetic, fine for UTC timestamps
print("+3600 s:  ", iso.string(from: start.addingTimeInterval(3600)))

Output

One day after January 31 is 2026-02-01, and one day before is 2026-01-30. One month after January 31 is 2026-02-28, since February has no 31st, while two months lands on 2026-03-31: each call starts from the original date. Adding one month twice in a row gives March 28 instead, because the second step starts from February 28. The combined DateComponents(month: 1, day: 10, hour: 6) gives 2026-03-10T16:00:00Z, and February 29, 2024 plus a year is 2025-02-28. addingTimeInterval(3600) adds exact seconds, which is safe in UTC but not for whole days in a zone with daylight saving time.

4Calendar days vs 24-hour periods across daylight saving time

In a zone that switches to daylight saving time, the day of the switch is 23 hours long (and the day it switches back is 25). So adding 86400 seconds and adding one calendar day give different results, and a two-day gap can be 47 hours. A related trap: dateComponents([.day], …) counts whole days from the start time, so 11:30 pm to 12:15 am the next morning is zero days. When you want the number of dates between two moments, as in "due in 3 days", move both to startOfDay(for:) first. The example uses New York, where clocks jump from 2:00 to 3:00 on March 8, 2026.

daylight_saving.swift
import Foundation

// New York moves its clocks from 2:00 to 3:00 on March 8, 2026
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "America/New_York")!

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = calendar.timeZone
formatter.dateFormat = "MMM d HH:mm zzz"

let noon = calendar.date(from: DateComponents(
    year: 2026, month: 3, day: 7, hour: 12))!
print("start:     ", formatter.string(from: noon))

// One calendar day keeps the wall-clock time; 86,400 seconds does not
let nextDay = calendar.date(byAdding: .day, value: 1, to: noon)!
let plus24h = noon.addingTimeInterval(86_400)
print("+1 day:    ", formatter.string(from: nextDay))
print("+86400 s:  ", formatter.string(from: plus24h))

// Noon to noon two days later: two calendar days, but only 47 hours
let later = calendar.date(byAdding: .day, value: 2, to: noon)!
let dayCount = calendar.dateComponents([.day], from: noon, to: later).day!
print("days:      ", dayCount)
print("hours:     ", later.timeIntervalSince(noon) / 3600)

// 11:30 pm to 12:15 am is 45 minutes: zero whole days, one date change
let lateNight = calendar.date(from: DateComponents(
    year: 2026, month: 3, day: 9, hour: 23, minute: 30))!
let afterMidnight = calendar.date(byAdding: .minute, value: 45, to: lateNight)!
let whole = calendar.dateComponents([.day], from: lateNight,
                                    to: afterMidnight).day!
let dates = calendar.dateComponents(
    [.day],
    from: calendar.startOfDay(for: lateNight),
    to: calendar.startOfDay(for: afterMidnight)).day!
print("whole days:", whole, "| dates apart:", dates)

Output

Starting from Mar 7 12:00 EST, one calendar day gives Mar 8 12:00 EDT, but 86,400 seconds gives Mar 8 13:00 EDT, an hour off, because March 8 had only 23 hours. Noon to noon two days later counts as 2 days but 47.0 hours. The last line shows the midnight case: whole days: 0 | dates apart: 1. Always pass a zone identifier such as America/New_York, not a fixed offset, so the calendar knows the daylight saving rules.

5Turn seconds into hours, minutes and seconds

To split a whole number of seconds, divide by 3,600 for hours, then divide the remainder by 60 for minutes; what is left is seconds. quotientAndRemainder(dividingBy:) does each division and remainder in one call, and String(format: "%02d:%02d:%02d", …) pads each part to two digits. For display, the standard library's Duration type (Swift 5.7) formats itself with Foundation: .time(pattern:) for a clock style and .units(…) for words. Spelled-out units depend on the locale, which follows the user's device by default, so the example pins en_US.

seconds_to_hms.swift
import Foundation

// Integer division and remainder split a count of seconds
func hms(_ total: Int) -> (hours: Int, minutes: Int, seconds: Int) {
    let (hours, rest) = total.quotientAndRemainder(dividingBy: 3600)
    let (minutes, seconds) = rest.quotientAndRemainder(dividingBy: 60)
    return (hours, minutes, seconds)
}

let total = 8130
let parts = hms(total)
print(parts.hours, "h", parts.minutes, "min", parts.seconds, "s")

// %02d pads with a leading zero: a clock-style string
let clock = String(format: "%02d:%02d:%02d",
                   parts.hours, parts.minutes, parts.seconds)
print(clock)

// The same with plain / and %
print(total / 3600, (total % 3600) / 60, total % 60)

// Duration (Swift 5.7) formats itself
let us = Locale(identifier: "en_US")
let duration = Duration.seconds(total)
print(duration.formatted(.time(pattern: .hourMinuteSecond)))
print(duration.formatted(
    .time(pattern: .hourMinuteSecond(padHourToLength: 2))))
print(Duration.seconds(95).formatted(.time(pattern: .minuteSecond)))
print(duration.formatted(
    .units(allowed: [.hours, .minutes, .seconds], width: .wide)
    .locale(us)))

// From a TimeInterval: days and hours, at most two units
let interval: TimeInterval = 183_650
print(Duration.seconds(interval).formatted(
    .units(allowed: [.days, .hours, .minutes, .seconds], width: .wide,
           maximumUnitCount: 2)
    .locale(us)))

Output

8,130 seconds is 2 h 15 min 30 s, or 02:15:30 with %02d. The Duration patterns print 2:15:30, or 02:15:30 with padHourToLength: 2, and 95 seconds as 1:35. Hours don't wrap at 24: 100,000 seconds prints as 27:46:40. A fractional TimeInterval is rounded, so 8,130.6 seconds prints as 2:15:31. The units style gives 2 hours, 15 minutes, 30 seconds, and maximumUnitCount: 2 keeps the two largest: 2 days, 3 hours. DateComponentsFormatter, the older Apple answer, doesn't compile on Linux here ("Not supported in swift-corelibs-foundation").

6Which should you use?

MethodGivesTime zone mattersBest for
calendar.dateComponents([.day], from:to:)Whole units, Int?Yes, set itDays, months or years between dates
dateComponents([.year, .month, .day, …])A breakdownYes, set itAges, "2 years 1 month" displays
end.timeIntervalSince(start)Seconds, DoubleNoElapsed time, timers, durations
calendar.date(byAdding: .day, value: 1, to:)Same wall-clock timeYes, set itAdding days, months, years
date.addingTimeInterval(86400)Exactly 24 h laterIgnores itUTC timestamps only
startOfDay(for:) on both datesDates apartYes, set it"Due in 3 days" counts
Duration.seconds(n).formatted(…)2:15:30, 2 hours, …NoShowing a length of time

Frequently asked questions

How do I add 1 day to a Date in Swift?

Use a calendar: Calendar.current.date(byAdding: .day, value: 1, to: date)!. It returns an optional, nil only when the date cannot be built. Avoid date.addingTimeInterval(86400) for whole days: on the day clocks spring forward it lands an hour late, as section 4 shows (Mar 8 13:00 EDT instead of Mar 8 12:00 EDT). Use a negative value to go back a day.

How do I get the number of days between two dates?

calendar.dateComponents([.day], from: start, to: end).day! counts whole days, so 23 hours is 0 days. To count calendar dates instead (11:30 pm to 12:15 am is 1), pass calendar.startOfDay(for: start) and calendar.startOfDay(for: end). Set the calendar's time zone, because which date an instant falls on depends on it.

Why is my day count or added date off by one hour or one day?

Usually the time zone. Calendar.current and DateFormatter use the device's zone, so midnight UTC can be the previous evening locally, and a day with a daylight saving switch is 23 or 25 hours long. Create a calendar with an explicit timeZone, add days with date(byAdding:) rather than multiples of 86,400 seconds, and format dates with the same zone you calculated in.

How do I convert a TimeInterval to hours or minutes?

Divide: interval / 3600 is hours and interval / 60 is minutes, both as Double. Int(interval / 3600) gives whole hours and drops the rest, rounding toward zero. For hours, minutes and seconds together, convert to Int and use quotientAndRemainder(dividingBy:), or format Duration.seconds(interval).

Can I use DateComponentsFormatter or RelativeDateTimeFormatter?

On Apple platforms, yes. In Foundation on Linux here, DateComponentsFormatter fails to compile with "'DateComponentsFormatter' is unavailable: Not supported in swift-corelibs-foundation", and RelativeDateTimeFormatter gives "cannot find 'RelativeDateTimeFormatter' in scope". Duration with .formatted(.units(...)) covers "2 days, 3 hours" and works here.

Why does %02d print 00:-1:-35 for a negative number of seconds?

Integer division and % keep the sign: -95 / 60 is -1 and -95 % 60 is -35, so each part comes out negative. Take abs(total), split that, and put a minus sign in front yourself when the total is negative. Duration.seconds(-95) with the .hourMinuteSecond pattern already prints -0:01:35.

How do I show only the largest unit, like "2 days"?

Pass maximumUnitCount: 1 to the units style: Duration.seconds(183_650).formatted(.units(allowed: [.days, .hours, .minutes, .seconds], width: .wide, maximumUnitCount: 1)) prints 2 days with an en_US locale. To pick the unit yourself, ask dateComponents for [.year, .month, .day, .hour, .minute] and use the first field that is not zero.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground