/**
* 是否为今年
*/
- (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;
}
/**
* 是否为今天
*/
- (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;
}
+ (NSString *)stringWithTimeStr:(NSString *)timeStr
{
// 1.创建时间格式化工具类
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 2.格式时间
// 指定时间的格式
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh"];
NSDate *uploadTime = [formatter dateFromString:timeStr];
// 利用服务器的和本地时间进行对比
NSDateComponents *cmps = [uploadTime deltaWithNow];
if ([uploadTime isThisYear]) {
// 是今年
if ([uploadTime isToday]) {
// 是今天
if (cmps.hour >= 1) {
//其它
formatter.dateFormat = @"HH:mm";
return [formatter stringFromDate:uploadTime];
} else if (cmps.minute <= 1) {
// 刚刚
return @"刚刚";
} else {
// 1个小时内
return [NSString stringWithFormat:@"%ld分钟前", (long)cmps.minute];
}
} else if ([uploadTime isYesterday]) {
// 是昨天
formatter.dateFormat = @"昨天";
return [formatter stringFromDate:uploadTime];
} else {
// 其它天
formatter.dateFormat = @"MM-dd";
return [formatter stringFromDate:uploadTime];
}
} else {
// 不是今年
formatter.dateFormat = @"YY-MM-dd";
return [formatter stringFromDate:uploadTime];
}
return @"1分钟以前";
}