关于昨天、明天的判断

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,代表明天

你可能感兴趣的:(关于昨天、明天的判断)