2

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.

jscs
  • 63,095
  • 13
  • 148
  • 192
14wml
  • 3,700
  • 11
  • 39
  • 93

1 Answers1

10

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.

Martin R
  • 510,973
  • 84
  • 1,183
  • 1,314
rmaddy
  • 307,833
  • 40
  • 508
  • 550