Comparing NSDates without time component Comparing NSDates without time component ios ios

Comparing NSDates without time component


Use this Calendar function to compare dates in iOS 8.0+

func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult


passing .day as the unit

Use this function as follows:

let now = Date()// "Sep 23, 2015, 10:26 AM"let olderDate = Date(timeIntervalSinceNow: -10000)// "Sep 23, 2015, 7:40 AM"var order = Calendar.current.compare(now, to: olderDate, toGranularity: .hour)switch order {case .orderedDescending:    print("DESCENDING")case .orderedAscending:    print("ASCENDING")case .orderedSame:    print("SAME")}// Compare to hour: DESCENDINGvar order = Calendar.current.compare(now, to: olderDate, toGranularity: .day)switch order {case .orderedDescending:    print("DESCENDING")case .orderedAscending:    print("ASCENDING")case .orderedSame:    print("SAME")}// Compare to day: SAME


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


Xcode 11.2.1, Swift 5 & Above

Checks whether the date has same day component.

Calendar.current.isDate(date1, equalTo: date2, toGranularity: .day)

Adjust toGranularity as your need.