1

I am following this post. But when i run this bellow code in playground, have a bit chance it will be print "false". I think the reason is microsecond when initialize Date object.

Have any better way? Or how to compare without microsecond?

let date1 = Date()
let date2 = Date()
print(date1)
print(date2)

print(date1 == date2)

UPDATE I tried to print in millisecond, but i saw they same. enter image description here

Trần Hữu Hiền
  • 872
  • 1
  • 9
  • 22

1 Answers1

2

Calender provides a convenient API to do that

let date1 = Date()
let date2 = Date()

let isInSameSecond = Calendar.current.compare(date1, to: date2, toGranularity: .second) == .orderedSame

Change toGranularity to the desired level.

vadian
  • 274,689
  • 30
  • 353
  • 361