此段代码返回的内容是:
time < 1min 返回“刚刚”;
1min < time < 1h 返回示“xx分钟前”;
1h < time < 24h 返回“今天 xx点xx分”;
24h < time < 48h 返回“昨天 xx点xx分”;
48h < time < 本年1月1日 返回“xx月xx日 xx点xx分”;
time > 本年1月1日 返回“xxxx年xx月xx日”。
“yyyy-MM-dd HH:mm”
/*
* 根据时间戳返回距离当前时间多久
* beTime 时间戳
* return 返回距离当前时间的字符串(刚刚,几分钟前,今天几点几分,昨天几点几分...)
*/
- (NSString *)distanceTimeWithBeforeTime:(double)beTime
{
NSTimeInterval now = [[NSDate date]timeIntervalSince1970];
double distanceTime = now - beTime;
NSDate *datenow = [NSDate date];
NSString *dateNowYearStr = [[NSString stringWithFormat:@"%@", datenow] substringWithRange:NSMakeRange(0, 4)];
NSString * distanceStr;
NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:beTime];
NSDateFormatter * df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy"];
NSString * yearStr = [df stringFromDate:beDate];
[df setDateFormat:@"HH:mm"];
NSString * timeStr = [df stringFromDate:beDate];
[df setDateFormat:@"dd"];
NSString * nowDay = [df stringFromDate:[NSDate date]];
NSString * lastDay = [df stringFromDate:beDate];
if (distanceTime < 60) {//小于一分钟
distanceStr = @"刚刚";
}
else if (distanceTime <60*60) {//时间小于一个小时
distanceStr = [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60];
}
else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]){//时间小于一天
distanceStr = [NSString stringWithFormat:@"今天 %@",timeStr];
}
else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){
if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr];
}
else{
[df setDateFormat:@"MM-dd HH:mm"];
distanceStr = [df stringFromDate:beDate];
}
}
else if([yearStr isEqualToString:dateNowYearStr]){ // 是本年
[df setDateFormat:@"MM-dd HH:mm"];
distanceStr = [df stringFromDate:beDate];
}
else{ // 不是本年
[df setDateFormat:@"yyyy-MM-dd"];
distanceStr = [df stringFromDate:beDate];
}
return distanceStr;
}
网友评论
if (distanceTime < 60) return @"刚刚";
if (distanceTime <60*60) {//时间小于一个小时
return [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60];