How to Calculate Date Difference in Swift

How to Calculate Date Difference in Swift

Written by

in

Quick answer: Use Calendar.current.dateComponents([.day, .hour, .minute, .second], from: startDate, to: endDate) to get the difference. For a human-readable string, use DateComponentsFormatter with allowedUnits and unitsStyle set to .full or .abbreviated.

Why this happens

Swift’s Date type represents a single point in time (seconds since the reference date). It does not store calendar units like days or months. To find the difference between two dates in calendar terms—days, hours, minutes—you must ask a Calendar to break the interval into DateComponents. The calendar handles variable month lengths, daylight-saving transitions, and leap years, which a simple division of seconds cannot.

The original question also mentions a PHP time() value. That function returns a Unix timestamp (seconds since 1970-01-01 UTC). In Swift you create a Date from that value with Date(timeIntervalSince1970: timestamp). Once both sides are Date instances, the same calendar-based approach applies.

How to fix it

1. Calendar.dateComponents – granular numeric components

The most flexible way is an extension on Date that wraps Calendar.current.dateComponents(_:from:to:). Each call asks for a single component so the result is an Int you can compare directly.

import Foundation

extension Date {
    /// Years between this date and another.
    func years(from date: Date) -> Int {
        Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
    }
    /// Months between this date and another.
    func months(from date: Date) -> Int {
        Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
    }
    /// Weeks between this date and another.
    func weeks(from date: Date) -> Int {
        Calendar.current.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
    }
    /// Days between this date and another.
    func days(from date: Date) -> Int {
        Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
    }
    /// Hours between this date and another.
    func hours(from date: Date) -> Int {
        Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
    }
    /// Minutes between this date and another.
    func minutes(from date: Date) -> Int {
        Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
    }
    /// Seconds between this date and another.
    func seconds(from date: Date) -> Int {
        Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
    }
}

Usage

let phpTimestamp: TimeInterval = 1_417_147_270   // example from PHP time()
let past = Date(timeIntervalSince1970: phpTimestamp)
let now = Date()

print(now.days(from: past))      // e.g. 3_200
print(now.hours(from: past))     // e.g. 76_800

Each call performs a separate calendar calculation. If you need several components at once, request them together (see the combined offset below).

2. DateComponentsFormatter – ready-made human-readable strings

When you only need a single, localized string like “2 hours” or “3 days”, DateComponentsFormatter does the work without custom logic.

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 1          // show only the largest non-zero unit
formatter.unitsStyle = .full            // "2 hours" vs "2h"
formatter.string(from: past, to: now)   // "3 months"

Change maximumUnitCount to 2 or 3 to show “3 months, 2 weeks”. Set unitsStyle = .abbreviated for “3mo 2w”.

3. Combined offset showing all non-zero units

The second Stack Overflow answer builds a string that includes every unit down to seconds (“1h 59m 20s”). This is useful for timers or precise logs.

extension Date {
    func offsetFrom(_ date: Date) -> String {
        let components: Set<Calendar.Component> = [.day, .hour, .minute, .second]
        let diff = Calendar.current.dateComponents(components, from: date, to: self)

        let seconds = "\(diff.second ?? 0)s"
        let minutes = "\(diff.minute ?? 0)m " + seconds
        let hours   = "\(diff.hour ?? 0)h " + minutes
        let days    = "\(diff.day ?? 0)d " + hours

        if let d = diff.day, d > 0 { return days }
        if let h = diff.hour, h > 0 { return hours }
        if let m = diff.minute, m > 0 { return minutes }
        if let s = diff.second, s > 0 { return seconds }
        return "0s"
    }
}

Usage

let start = DateComponents(calendar: .current, year: 2024, month: 1, day: 1, hour: 12).date!
let end   = DateComponents(calendar: .current, year: 2024, month: 1, day: 2, hour: 14, minute: 30, second: 15).date!

print(end.offsetFrom(start))   // "1d 2h 30m 15s"

This single calendar call is more efficient than multiple single-component calls when you need the full breakdown.

How to prevent it

  • Pick the right calendar – Calendar.current follows the user’s locale and time zone. For server-side or fixed-UTC logic, use Calendar(identifier: .gregorian) and set calendar.timeZone = TimeZone(secondsFromGMT: 0)!.
  • Avoid manual second math – Dividing timeIntervalSinceReferenceDate by 86_400 ignores daylight-saving shifts and leap seconds.
  • Reuse formatters – DateComponentsFormatter is expensive to create; keep a static instance if you call it frequently.
  • Handle optionals – dateComponents returns optional Int? for each component; always provide a default (?? 0).

FAQ

Why does days(from:) sometimes return one less than expected?

Calendar counts calendar day boundaries, not 24-hour multiples. If the start date is 23:00 and the end date is 01:00 the next day, the day component is 1 even though only two hours elapsed.

Can I get the difference in milliseconds?

Calendar.Component has no .millisecond or .nanosecond. For sub-second precision use end.timeIntervalSince(start) which returns a TimeInterval (seconds with fractional part). Multiply by 1_000 for milliseconds.

How do I parse a PHP time() integer in Swift?

let date = Date(timeIntervalSince1970: TimeInterval(phpTimestamp)). The PHP value is already UTC-based, so the resulting Date is correct regardless of the device’s time zone.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.