Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing NSDates without time component

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 ignore the time element. Is this possible in Swift? How can it be done? Even if I could set the time element to be the same time on every date that would work too.

Also, I am trying to compare two dates and at the moment I am using the following code:

var earlierDate:NSDate = firstDate.earlierDate(secondDate) 

Is this the only way or can I do this in a way that ignores the time element? For instance I don't want a result if they are the same day, but different times.

like image 692
agf119105 Avatar asked Jul 04 '14 15:07

agf119105


2 Answers

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: DESCENDING  var 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 
like image 162
Ashley Mills Avatar answered Nov 07 '22 07:11

Ashley Mills


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))         }     } } 
like image 34
slamor Avatar answered Nov 07 '22 08:11

slamor