0

I want to calculate the diff between two dates (for example '11 oct 2015' and '23 dec 2015') in multiple units in Swift. For these dates the result i want to achieve should be something like '2 months, 11 days'

In java using joda-time library i can make it with the following code:

PeriodType pt = PeriodType.standard()
    .withYearsRemoved()
    .withWeeksRemoved()
    .withHoursRemoved()
    .withMinutesRemoved()
    .withSecondsRemoved()
    .withMillisRemoved();
Period per = new Period(date1, date2, pt);
int months = per.getMonths()
int days = per.getDays()

How can i get the same result in Swift?

HoneyBooBoo
  • 55
  • 1
  • 7
  • 2
    Lookup NSCalendar and NSDateComponents ( and of course Apple's Data Programming Guide). There are lots of examples on SO. – Martin R Oct 10 '15 at 22:58

1 Answers1

0

The answer is on this page: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html#//apple_ref/doc/uid/TP40007836-SW8

In Swift:

func monthsDaysBetweenStartDate(startDate: NSDate, endDate: NSDate) -> (months: Int, days: Int)? {

    let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    let unitFlags: NSCalendarUnit = [NSCalendarUnit.Month, NSCalendarUnit.Day]
    if let components = gregorian?.components(unitFlags, fromDate: startDate, toDate: endDate, options: NSCalendarOptions()) {
        return (months: components.month, days: components.day)
    }
    return nil
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72