2017-02-17 108 views
6

我有兩個日期,我想比較它。 如何比較日期? 我必須約會對象。說modificateionDate舊的updatedDate如何在swift 3.0中比較日期?

那麼最好的做法是比較日期?

+2

的最佳實踐將獲得的意見。顯示「你」是如何比較日期並詢問是否有更好的方法? – JohnG

+0

看看[這個](http://stackoverflow.com/a/29319732/3844242) –

回答

8

Date現在符合Comparable協議。因此,您可以簡單地使用<,>==來比較兩個Date類型的對象。

if modificateionDate < updatedDate { 
    //modificateionDate is less than updatedDate 
} 
+1

@AshwinKanjariya你已經告訴你不得不'日期'實例,那麼這將工作,我認爲你有'NSDate'實例首先確認這裏顯示你的代碼。如果在Swift 3中使用'Date'而不是'NSDate' 3 –

+0

好吧確定謝謝 –

+1

是nirav ...謝謝 –

-1

Swift具有orderedAscending,orderedDescending和以下相同的ComparisonResult。

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

希望這可以幫助你。

+1

'Swift與orderedAscending'比較結果No.編號這是來自基金會。斯威夫特本身並沒有這些。 – Moritz

+0

現在我100%確定這兩個a/c都是由你@AshwinIndianic處理的。你認爲你改變了這個用戶的名字,你在這裏活了下來:P:D很高興: - –

+0

謝謝你的注意,但你認爲是不正確的......你可以爲此詳細介紹我不介意。 –

4

Per @ NiravD的回答,DateComparable。不過,如果你想比較給定的粒度,可以使用Calendarcompare(_:to:toGranularity:)

例...

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 
+0

謝謝!這個粒度函數正是我正在尋找的。 – derf26

1

斯威夫特的iOS 8個,最多當你需要比簡單地放大或縮小多個日期比較。例如它是同一天還是前一天,...

注意:永遠不會忘記時區。日曆時區具有默認值,但如果您不喜歡默認值,則必須自行設置時區。要知道哪一天,你需要知道你在問什麼時區。

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) 
     } 
    } 

使用方法如下:

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

對於更復雜的例子如何在過濾器中使用此看到:

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