Do you know how to know if two NSDate
are the same day. I want to take into account the locale...
It could be easy to use a timeIntervalSinceDate:
but Monday 23H58 and Tuesday 00H01 are not in the same day...
Dealing with NSDate
and locale for calculation is not very easy.
To check if two dates are the same day, call the toDateString() method on both Date() objects and compare the results. If the output from calling the method is the same, the dates are the same day.
let date1 = Date() let date2 = Date(). addingTimeInterval(100) if date1 == date2 { ... } else if date1 > date2 { ... } else if date1 < date2 { ... } if i want to ignore time. e.g. 2019-05-14 12:08:14 +0000 == 2019-05-14 should return true.
Get current time in “YYYY-MM–DD HH:MM:SS +TIMEZONE” format in Swift. This is the easiest way to show the current date-time.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsForFirstDate = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:firstDate];
NSDateComponents *componentsForSecondDate = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:secondDate];
if ([componentsForFirstDate year] == [componentsForSecondDate year])
etc.
I don't know if isEquals
would do what you want on NSDateComponents
.
Since iOS 8 this is straightforward:
let isSameDay = NSCalendar.currentCalendar().isDate(date1, inSameDayAsDate: date2)
and it becomes a little simpler yet with Swift 3:
let isSameDay = Calendar.current.isDate(date1, inSameDayAs: date2)
Use NSCalendar and NSDateComponents for that:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps1 = [cal components:(NSMonthCalendarUnit| NSYearCalendarUnit | NSDayCalendarUnit)
fromDate:date1];
NSDateComponents *comps2 = [cal components:(NSMonthCalendarUnit| NSYearCalendarUnit | NSDayCalendarUnit)
fromDate:date2];
BOOL sameDay = ([comps1 day] == [comps2 day]
&& [comps1 month] == [comps2 month]
&& [comps1 year] == [comps2 year]);
Swift:
func isSameDays(date1:NSDate, _ date2:NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
var comps1 = calendar.components([NSCalendarUnit.Month , NSCalendarUnit.Year , NSCalendarUnit.Day], fromDate:date1)
var comps2 = calendar.components([NSCalendarUnit.Month , NSCalendarUnit.Year , NSCalendarUnit.Day], fromDate:date2)
return (comps1.day == comps2.day) && (comps1.month == comps2.month) && (comps1.year == comps2.year)
}
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