Comparing NSDates without time component

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

    There are several useful methods in NSCalendar in iOS 8.0+:

    startOfDayForDate, isDateInToday, isDateInYesterday, isDateInTomorrow
    

    And even to compare days:

    func isDate(date1: NSDate!, inSameDayAsDate date2: NSDate!) -> Bool
    

    To ignore the time element you can use this:

    var toDay = Calendar.current.startOfDay(for: Date())
    

    But, if you have to support also iOS 7, you can always write an extension

    extension NSCalendar {
        func myStartOfDayForDate(date: NSDate!) -> NSDate!
        {
            let systemVersion:NSString = UIDevice.currentDevice().systemVersion
            if systemVersion.floatValue >= 8.0 {
                return self.startOfDayForDate(date)
            } else {
                return self.dateFromComponents(self.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: date))
            }
        }
    }
    

提交回复
热议问题