Search code examples
iosswiftdateswift2ios9

Calculate duration between date ios in Years, months and date format


Im new at swift programming and i havent been able successfully find code to find difference between two dates in terms of years , months and days. I tried the following code but it didnt work

let form = NSDateComponentsFormatter()
form.maximumUnitCount = 2
form.unitsStyle = .Full
let s = form.stringFromTimeInterval( date2.timeIntervalSinceReferenceDate - date1.timeIntervalSinceReferenceDate)

Input

Date1 = "12/March/2015"

Date2 = "1/June/2015"

Output : x years y months z days

Please advice


Solution

  • If you need the difference (in years, months, days) numerically then compute NSDateComponents as in Swift days between two NSDates or Rajan's answer.

    If you need the difference as a (localized) string to present it to the user, then use NSDateComponentsFormatter like this

    let form = NSDateComponentsFormatter()
    form.maximumUnitCount = 2
    form.unitsStyle = .Full
    form.allowedUnits = [.Year, .Month, .Day]
    let s = form.stringFromDate(date1, toDate: date2)
    

    As already mentioned in the comments, computing the difference from the pure time interval between the dates cannot give correct results because most information about the dates is lost.

    Update for Swift 3:

    let form = DateComponentsFormatter()
    form.maximumUnitCount = 2
    form.unitsStyle = .full
    form.allowedUnits = [.year, .month, .day]
    let s = form.string(from: date1, to: date2)