Trần Hữu Hiền
Trần Hữu Hiền

Reputation: 1044

How to compare 2 date without compare microsecond?

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

Upvotes: 1

Views: 61

Answers (1)

vadian
vadian

Reputation: 285220

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.

Upvotes: 2

Related Questions