iosswiftcocoa-touchnsdatenscalendar

Check whether two Dates are equal to minute precision


I want to check whether two dates are equal, where equal means they have the same value to the minute. I don't want to compare the seconds value.

Ex:

// should be equal
11/12/17 11:19:29
11/12/17 11:19:03

// not equal
11/12/17 11:19:59
11/12/17 11:20:00

One way I'm thinking of doing it is getting the time components and going through each one. But I'm wondering if there's a faster or cleaner way.


Solution

  • The Calendar class provides the compare(_:to:toGranularity:) method for this:

    let result = Calendar.current.compare(date1, to: date2, toGranularity: .minute)
    

    result will indicate whether date1 is >, =, or < than date2.