Comparing NSDates without time component

后端 未结 17 1747
轮回少年
轮回少年 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:06

    I wrote the following method to compare two dates by borrowing from Ashley Mills solution. It compares two dates and returns true if the two dates are the same (stripped of time).

    func compareDate(date1:NSDate, date2:NSDate) -> Bool {
        let order = NSCalendar.currentCalendar().compareDate(date1, toDate: date2,
            toUnitGranularity: .Day)
        switch order {
        case .OrderedSame:
            return true
        default:
            return false
        }
    }
    

    And it is called like this:

    if compareDate(today, date2: anotherDate) {
        // The two dates are on the same day.
    }
    

提交回复
热议问题