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,694
  • 13
  • 151
  • 195
14wml
  • 4,048
  • 11
  • 49
  • 97

2 Answers2

11

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
  • 529,903
  • 94
  • 1,240
  • 1,382
rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

Swift 5

You can return a boolean value:

let dateCompare = Calendar.current.isDate(date1, equalTo: date2, toGranularity: .minute)

if dateCompare == false {
   // Different date, hour and minute
} else {
   // Same date, hour and minute
}
awex
  • 130
  • 3
  • 7