Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare date in swift 3.0?

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

So which is the best practice to compare dates?

like image 858
Ashwin Indianic Avatar asked Feb 17 '17 09:02

Ashwin Indianic


Video Answer


3 Answers

Date now conforms to Comparable protocol. So you can simply use <, > and == to compare two Date type objects.

if modificateionDate < updatedDate {
     //modificateionDate is less than updatedDate
}
like image 169
Nirav D Avatar answered Sep 30 '22 01:09

Nirav D


Per @NiravD's answer, Date is Comparable. However, if you want to compare to a given granularity, you can use Calendar's 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
like image 44
Ashley Mills Avatar answered Sep 30 '22 01:09

Ashley Mills


Swift iOS 8 and up When you need more than simply bigger or smaller date comparisons. For example is it the same day or the previous day,...

Note: Never forget the timezone. Calendar timezone has a default, but if you do not like the default, you have to set the timezone yourself. To know which day it is, you need to know in which timezone 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 like this:

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

For a more complex example how to use this in a filter see this:

https://stackoverflow.com/a/45746206/4946476

like image 20
t1ser Avatar answered Sep 30 '22 02:09

t1ser