Comparing NSDates without time component

后端 未结 17 1613
轮回少年
轮回少年 2020-11-27 12:49

In a swift playground, I have been using

NSDate.date() 

But, this always appears with the time element appended. For my app I need to ignor

17条回答
  •  有刺的猬
    2020-11-27 13:22

    I wrote a Swift 4 extension for comparing two dates:

    import Foundation
    
    extension Date {      
      func isSameDate(_ comparisonDate: Date) -> Bool {
        let order = Calendar.current.compare(self, to: comparisonDate, toGranularity: .day)
        return order == .orderedSame
      }
    
      func isBeforeDate(_ comparisonDate: Date) -> Bool {
        let order = Calendar.current.compare(self, to: comparisonDate, toGranularity: .day)
        return order == .orderedAscending
      }
    
      func isAfterDate(_ comparisonDate: Date) -> Bool {
        let order = Calendar.current.compare(self, to: comparisonDate, toGranularity: .day)
        return order == .orderedDescending
      }
    }
    

    Usage:

    startDate.isSameDateAs(endDate) // returns a true or false

提交回复
热议问题