Reputation: 1005
I am trying to compare if a time is in today. I used the NSCalendar [Calender isDateInToday:date]
method. However, a time just passed midnight fail the test.
Time 00:14:05 returns NO but 21:43:47 returns YES.
My test code:
NSCalendar *cal = [NSCalendar calendarWithIdentifier: NSCalendarIdentifierGregorian];
NSLog(@"date: %@, isInToday: %i, Currernt date: %@", o.deliverDate, [cal isDate:o.deliverDate inSameDayAsDate:[TimeIntervals getCurrerntLocalTime]], [TimeIntervals getCurrerntLocalTime]);
where[TimeIntervals getCurrerntLocalTime]
returns current local system time:
+(NSDate *)getCurrerntLocalTime{
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
return destinationDate;
}
And result is:
date: 2015-02-09 00:14:05 +0000, isInToday: 0, Currernt date: 2015-02-09 19:07:43 +0000
date: 2015-02-09 21:43:47 +0000, isInToday: 1, Currernt date: 2015-02-09 19:07:44 +0000
Any suggestions?
Upvotes: 1
Views: 2110
Reputation: 873
You should take your current Calendar:
In swift:
let isToday = NSCalendar.currentCalendar().isDateInToday(date)
Upvotes: 6