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.
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
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)) } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With