在移动开发中很有可能遇到需要展示几天前的,几分钟前的时间格式
如上图
可以通过以下的简单地解决办法:
+(NSString *)dateIntelligentFormat:(NSDate *)date{
NSInteger interval = fabs([date timeIntervalSinceNow]);
if(interval < 60){
return @"刚刚";
}else if(interval < 60*60){
NSInteger time = interval/60;
return [NSString stringWithFormat:@"%ld分钟前",(long)time];
}else if(interval < 24*60*60){
NSInteger time = interval/60/60;
return [NSString stringWithFormat:@"%ld小时前",(long)time];
}else if(interval < 30*24*60*60){
NSInteger time = interval/24/60/60;
return [NSString stringWithFormat:@"%ld天前",(long)time];
}else if(interval < 12*30*24*60*60){
NSInteger time = interval/30/24/60/60;
return [NSString stringWithFormat:@"%ld月前",(long)time];
}else{
NSInteger time = interval/12/30/24/60/60;
return [NSString stringWithFormat:@"%ld年前",(long)time];
}
}