alanvabraham alanvabraham - 2 months ago 13
Swift Question

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

Answer

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 NSDateFormatter 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.

Comments