How to compare date in swift 3.0?

I have two dates, and I want to compare it. How can I compare dates? I mean objects. Say modificateionDate older than updatedDate .

So what is the best way to compare dates?

+6
source share
4 answers

Date now complies with the Comparable protocol. Therefore, you can simply use < , > and == to compare two Date objects.

 if modificateionDate < updatedDate { //modificateionDate is less than updatedDate } 
+9
source

In @NiravD's answer, Date is Comparable . However, if you want to compare with a specific granularity, you can use Calendar compare(_:to:toGranularity:)

Example...

 let dateRangeStart = Date() let dateRangeEnd = Date().addingTimeInterval(1234) // Using granularity of .minute let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .minute) switch order { case .orderedAscending: print("\(dateRangeEnd) is after \(dateRangeStart)") case .orderedDescending: print("\(dateRangeEnd) is before \(dateRangeStart)") default: print("\(dateRangeEnd) is the same as \(dateRangeStart)") } > 2017-02-17 10:35:48 +0000 is after 2017-02-17 10:15:14 +0000 // Using granularity .hour let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .hour) > 2017-02-17 10:37:23 +0000 is the same as 2017-02-17 10:16:49 +0000 
+4
source

Swift iOS 8 and . If you need more than just bigger or smaller date mappings. For example, this is the same day or the previous day, ...

Note: Never forget the time zone. The time zone of the calendar has a default value, but if you do not like the default value, you must set the time zone yourself. To find out which day you need to know what time zone you are asking.

 extension Date { func compareTo(date: Date, toGranularity: Calendar.Component ) -> ComparisonResult { var cal = Calendar.current cal.timeZone = TimeZone(identifier: "Europe/Paris")! return cal.compare(self, to: date, toGranularity: toGranularity) } } 

Use it as follows:

 if thisDate.compareTo(date: Date(), toGranularity: .day) == .orderedDescending { // thisDate is a previous day } 

For a more complex example of using this in a filter, see this:

fooobar.com/questions/44168 / ...

+1
source

Swift has a ComparisonResult with an ordered attribute, ordered, reduced, and the same as shown below.

 if modificateionDate.compare(updatedDate) == ComparisonResult.orderedAscending { //Do what you want } 

Hope this can help you.

-one
source

Source: https://habr.com/ru/post/1015056/


All Articles