Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 893
alanvabraham Avatar asked Nov 18 '15 12:11

alanvabraham


2 Answers

We can use this function in Swift 2.0

func yearsBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Year], fromDate: startDate, toDate: endDate, options: [])

    return components.year
}

You can return anything like I returned year in this function. This will return number of years between the two dates.
You can just write months,days etc in order to find the difference between the two dates in months and days respectively.

Edit

Swift 3.0 and Above

func yearsBetweenDate(startDate: Date, endDate: Date) -> Int {

    let calendar = Calendar.current

    let components = calendar.dateComponents([.year], from: startDate, to: endDate)

    return components.year!
}
like image 95
Rajan Maheshwari Avatar answered Oct 30 '22 15:10

Rajan Maheshwari


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)
like image 35
Martin R Avatar answered Oct 30 '22 16:10

Martin R