从iOS 8
开始,苹果在NSCalendar
中为我们直接提供了用于昨天
和今天
判断的API
/*
This API reports if the date is within "yesterday".
*/
- (BOOL)isDateInYesterday:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
/*
This API reports if the date is within "tomorrow".
*/
- (BOOL)isDateInTomorrow:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
在iOS 8
之前,还是需要我们手动实现的,示例代码:
// 判断传入的date对象是否是昨天
- (BOOL)isYesterday {
NSDateComponents *components = [self dateComponentsToNow];
return components.year == 0 && components.month == 0 && components.day == 1;
}
// 判断传入的date对象是否是明天
- (BOOL)isTomorrow {
NSDateComponents *components = [self dateComponentsToNow];
return components.year == 0 && components.month == 0 && components.day == -1;
}
// 将当前date转换为特定格式的字符串date
- (NSString *)dateformatterString:(NSString *)dateformatter {
[JSDateFormatter sharedDateFormatterManager].dateFormat = dateformatter;
return [[JSDateFormatter sharedDateFormatterManager] stringFromDate:self];
}
// 日期比较 传入的NSDate对象和[NSDate date]的比较返回值
- (NSDateComponents *)dateComponentsToNow {
NSString *selfString = [self dateformatterString:@"yyyyMMdd"];;
NSString *nowString = [[NSDate date] dateformatterString:@"yyyyMMdd"];
NSDate *selfDate = [[JSDateFormatter sharedDateFormatterManager] dateFromString:selfString];
NSDate *nowDate = [[JSDateFormatter sharedDateFormatterManager] dateFromString:nowString];
NSCalendar *calendar = nil;
if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *components = [calendar components:unit fromDate:selfDate toDate:nowDate options:0];
return components;
}
- 实现思路:
- 忽略掉
时分秒的干扰
,先将NSDate
对象转成只包含年月日
的字符串,再将转换后的字符串日期转换回NSDate
对象,[NSDate date]
同样也是 - 这样我们需要判断的
NSDate
对象和当前日期对象就都只包含年月日
,再通过NSCalendar
进行比较,如果.day
相差1
,代表为昨天
;如果.day
相差-1
,代表明天
- 忽略掉