項(xiàng)目用到了從服務(wù)器返回距離1970年多少秒的發(fā)布的數(shù)據(jù),然后計(jì)算多少當(dāng)前時(shí)間距離消息發(fā)布的時(shí)間,1分鐘以?xún)?nèi)顯示幾秒前,1小時(shí)以?xún)?nèi)顯示幾分鐘前,1天以?xún)?nèi)顯示幾小時(shí)前,超過(guò)一天則顯示具體日期,這是需求。
為此我做了一個(gè) NSDate的擴(kuò)展類(lèi),分享給大家
#import "NSDate+Extention.h"
@implementation NSDate (Extention)`
+ (NSString *)nowFromDateExchange:(int)oldTime {//oldTime 為服務(wù)器返回的發(fā)布消息時(shí)間距離1970年多少秒
// 計(jì)算現(xiàn)在距1970年多少秒
NSDate *date = [NSDate date];
NSTimeInterval currentTime= [date timeIntervalSince1970];
// 計(jì)算現(xiàn)在的時(shí)間和發(fā)布消息的時(shí)間時(shí)間差
double timeDiffence = currentTime - oldTime;
// 根據(jù)秒數(shù)的時(shí)間差的不同,返回不同的日期格式
if (timeDiffence <= 60) {
return [NSString stringWithFormat:@"%.0f 秒前",timeDiffence];
}else if (timeDiffence <= 3600){
return [NSString stringWithFormat:@"%.0f 分鐘前",timeDiffence / 60];
}else if (timeDiffence <= 86400){
return [NSString stringWithFormat:@"%.0f 小時(shí)前",timeDiffence / 3600];
}else if (timeDiffence <= 604800){
return [NSString stringWithFormat:@"%.0f 天前",timeDiffence / 3600 /24];
}else{
// 返回具體日期
NSDate *oldTimeDate = [NSDate dateWithTimeIntervalSince1970:oldTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
return [formatter stringFromDate:oldTimeDate];
}
}
@end
再此附上 github 地址:https://github.com/D-james/NSDate-Extention