本文共 2742 字,大约阅读时间需要 9 分钟。
@interface NSDate (LC)/// 是否为今天- (BOOL)isToday;/// 是否为昨天- (BOOL)isYesterday;/// 是否为今年- (BOOL)isThisYear;/// 返回年月日- (NSDate *)dateWithYMD;/// 获得与当前时间的差距- (NSDateComponents *)deltaWithNow;/// 返回日期字符串- (NSString *)dateString;@end
#import "NSDate+LC.h"@implementation NSDate (LC)/// 是否为今天- (BOOL)isToday{ NSCalendar *calendar = [NSCalendar currentCalendar]; int unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear; // 1.获得当前时间的年月日 NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]]; // 2.获得self的年月日 NSDateComponents *selfCmps = [calendar components:unit fromDate:self]; return (selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day);}- (BOOL)isYesterday{ NSDate *nowDate = [[NSDate date] dateWithYMD]; NSDate *selfDate = [self dateWithYMD]; // 获得nowDate和selfDate的差距 NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *cmps = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0]; return cmps.day == 1;}/// 返回年月日- (NSDate *)dateWithYMD{ NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd"; NSString *selfStr = [fmt stringFromDate:self]; return [fmt dateFromString:selfStr];}/// 是否为今年- (BOOL)isThisYear{ NSCalendar *calendar = [NSCalendar currentCalendar]; int unit = NSCalendarUnitYear; // 1.获得当前时间的年月日 NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]]; // 2.获得self的年月日 NSDateComponents *selfCmps = [calendar components:unit fromDate:self]; return nowCmps.year == selfCmps.year;}- (NSDateComponents *)deltaWithNow{ NSCalendar *calendar = [NSCalendar currentCalendar]; int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];}- (NSString *)dateString{ NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; //判断时间 和 现在时间 的差距 if (self.isToday) { // 今天 if (self.deltaWithNow.hour >= 1) { return [NSString stringWithFormat:@"%d小时前", (int)self.deltaWithNow.hour]; } else if (self.deltaWithNow.minute >= 1) { return [NSString stringWithFormat:@"%d分钟前", (int)self.deltaWithNow.minute]; } else { return @"刚刚"; } } else if (self.isYesterday) { // 昨天 fmt.dateFormat = @"昨天 HH:mm"; return [fmt stringFromDate:self]; } else if (self.isThisYear) { // 今年(至少是前天) fmt.dateFormat = @"MM-dd HH:mm"; return [fmt stringFromDate:self]; } else { // 非今年 fmt.dateFormat = @"yyyy-MM-dd HH:mm"; return [fmt stringFromDate:self]; }}@end
转载地址:http://tfkii.baihongyu.com/