In Swift 5 and iOS 12, you can use one of the 3 solutions below to calculate the difference (in years, months, days) between two dates.
# 1. Using Calendar dateComponents(_:from:to:) method
Calendar is the dateComponents(_:from:to:) method. dateComponents(_:from:to:) has the following declaration:
func dateComponents(_ components: Set<Calendar.Component>, from start: DateComponents, to end: DateComponents) -> DateComponents
Returns the difference between the two dates specified as DateComponents .
The Playground example below shows how to use dateComponents(_:from:to:) to calculate the difference between two dates:
import Foundation let calendar = Calendar.current let startComponents = DateComponents(year: 2010, month: 11, day: 22) let endComponents = DateComponents(year: 2015, month: 5, day: 1) let dateComponents = calendar.dateComponents([.year, .month, .day], from: startComponents, to: endComponents) print(dateComponents) // prints: year: 4 month: 5 day: 9 isLeapMonth: false
# 2. Using Calendar dateComponents(_:from:to:) method
Calendar is the dateComponents(_:from:to:) method. dateComponents(_:from:to:) has the following declaration:
func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents
Returns the difference between two dates.
The Playground example below shows how to use dateComponents(_:from:to:) to calculate the difference between two dates:
import Foundation let calendar = Calendar.current let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))! let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))! let dateComponents = calendar.dateComponents([.year, .month, .day], from: startDate, to: endDate) print(dateComponents)
# 3. Using string(from:to:) DateComponentsFormatter string(from:to:) method
DateComponentsFormatter has a method called string(from:to:) . string(from:to:) has the following declaration:
func string(from startDate: Date, to endDate: Date) -> String?
Returns a formatted string based on the time difference between two dates.
The Playground example below shows how to use string(from:to:) to calculate the difference between two dates:
import Foundation let calendar = Calendar.current let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))! let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))! let formatter = DateComponentsFormatter() formatter.unitsStyle = .full formatter.allowedUnits = [.year, .month, .day] let string = formatter.string(from: startDate, to: endDate)! print(string)