Swift – Get Difference between Two Dates

In this tutorial, we will learn how to calculate the difference between two dates in Swift. We will use the Date, Calendar, and DateComponents classes to compute the difference in days, months, years, or other time units.


Getting the Difference Between Two Dates

In Swift, you can calculate the difference between two dates using the Calendar class. The dateComponents(_:from:to:) method allows you to specify the units (e.g., days, months, years) for which you want to calculate the difference.

Here’s an example to calculate the difference in days between two dates:

</>
Copy
import Foundation

let calendar = Calendar.current

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let startDate = dateFormatter.date(from: "2024-11-01")!
let endDate = dateFormatter.date(from: "2024-11-19")!

let components = calendar.dateComponents([.day], from: startDate, to: endDate)
if let days = components.day {
    print("Difference in days: \(days)")
}

In this example, the output will show the number of days between the two dates.


Calculating the Difference in Multiple Units

You can calculate the difference in multiple units such as days, months, and years by specifying them in the dateComponents method. Here’s an example:

</>
Copy
let components = calendar.dateComponents([.year, .month, .day], from: startDate, to: endDate)

if let years = components.year, let months = components.month, let days = components.day {
    print("Difference: \(years) years, \(months) months, \(days) days")
}

Explanation:

  • dateComponents(_:from:to:): Calculates the difference between two dates for the specified units.
  • .year, .month, .day: Specifies the units to calculate (e.g., years, months, days).
  • components.year, components.month, components.day: Accesses the calculated values for each unit.

Handling Date Differences in Hours, Minutes, and Seconds

You can also calculate the difference in smaller units such as hours, minutes, and seconds. Here’s an example:

</>
Copy
let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: startDate, to: endDate)

if let hours = timeComponents.hour, let minutes = timeComponents.minute, let seconds = timeComponents.second {
    print("Difference: \(hours) hours, \(minutes) minutes, \(seconds) seconds")
}

This can be useful for time-based calculations or measuring elapsed time.


Complete Swift Program

Here’s the complete Swift program to calculate the difference between two dates:

main.swift

</>
Copy
import Foundation

let calendar = Calendar.current

// Initialize the date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

// Define start and end dates
let startDate = dateFormatter.date(from: "2024-11-01")!
let endDate = dateFormatter.date(from: "2024-11-19")!

// Calculate the difference in days
let dayComponents = calendar.dateComponents([.day], from: startDate, to: endDate)
if let days = dayComponents.day {
    print("Difference in days: \(days)")
}

// Calculate the difference in years, months, and days
let fullComponents = calendar.dateComponents([.year, .month, .day], from: startDate, to: endDate)
if let years = fullComponents.year, let months = fullComponents.month, let days = fullComponents.day {
    print("Difference: \(years) years, \(months) months, \(days) days")
}

// Calculate the difference in hours, minutes, and seconds
let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: startDate, to: endDate)
if let hours = timeComponents.hour, let minutes = timeComponents.minute, let seconds = timeComponents.second {
    print("Difference: \(hours) hours, \(minutes) minutes, \(seconds) seconds")
}

Output:

Difference in days: 18
Difference: 0 years, 0 months, 18 days
Difference: 432 hours, 0 minutes, 0 seconds
Program ended with exit code: 0

Xcode Screenshot:

Swift Program to Get Difference between Two Dates