发帖时间分类
- 今年
- 今天
- 大于1小时 (xxx小时之前)
- 小于1小时,大于1分钟 (xxx分钟之前)
- 其它(1分钟内) (刚刚发布)
- 昨天 (昨天 17:25)
- 其它 (月-日 时:分:秒)
- 不是今年 ( (年-月-日 时:分:秒)
创建NSDate+LQLExtension
#import <Foundation/Foundation.h>
@interface NSDate (LQLExtension)
//比较from与self的时间差值
- (NSDateComponents *)deltaFrom:(NSDate *)from;
/**
* 是否为今年
*/
- (BOOL)isThisYear;
/**
* 是否为今天
*/
- (BOOL)isToday;
/**
* 是否为昨天
*/
- (BOOL)isYesterday;
@end
#import "NSDate+LQLExtension.h"
@implementation NSDate (LQLExtension)
- (NSDateComponents *)deltaFrom:(NSDate *)from {
//日历
NSCalendar *calender = [NSCalendar currentCalendar];
//比较时间
NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
return [calender components:unit fromDate:from toDate:self options:0];
}
//[NSDate date] 当前时间
- (BOOL)isThisYear {
//日历
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger nowYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger selfYear = [calendar component:NSCalendarUnitYear fromDate:self];
return nowYear == selfYear;
}
- (BOOL)isToday {
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
NSString *nowString = [fmt stringFromDate:[NSDate date]];
NSString *selfString = [fmt stringFromDate:self];
return [nowString isEqualToString:selfString];
}
- (BOOL)isYesterday {
//日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
NSDate *nowDate = [fmt dateFromString:[fmt stringFromDate:[NSDate date]]];
NSDate *selfDate = [fmt dateFromString:[fmt stringFromDate:self]];
//日历
NSCalendar *calendar = [NSCalendar currentCalendar];
//比较时间
NSDateComponents *cmps = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
fromDate:selfDate toDate:nowDate options:0];
return cmps.year == 0 && cmps.month == 0 && cmps.day == 1;
}
@end
帖子模型
/** 发帖时间*/
@property (nonatomic, copy) NSString *create_time;
- (NSString *)create_time {
//日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//设置日期格式:根据格式才可以解析
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//帖子创建时间
NSDate *create = [fmt dateFromString:_create_time];
if (create.isThisYear) {//今年
if (create.isToday) {//今天
NSDateComponents *cmps = [[NSDate date]deltaFrom:create];
if (cmps.hour >= 1) {//大于等于1小时
return [NSString stringWithFormat:@"%zd小时前",cmps.hour];
}else if (cmps.minute >= 1){//小于1小时,大于等于1分钟
return [NSString stringWithFormat:@"%zd分钟前",cmps.minute];
}else {//1分钟内
return @"刚刚";
}
}else if (create.isYesterday){//昨天
fmt.dateFormat = @"昨天 HH:mm:ss";
return [fmt stringFromDate:create];
}else {//其它
fmt.dateFormat = @"MM-dd HH:mm:ss";
return [fmt stringFromDate:create];
}
}else{//不是今年
return _create_time;
}
}