iOS 時間戳轉換為幾分鐘前等
阿新 • • 發佈:2018-11-02
該構造方法將時間戳轉換為幾分鐘前/幾小時前/幾天前/幾年前
//createTimeString為後臺傳過來的13位純數字時間戳
- (NSString *)updateTimeForRow:(NSString *)createTimeString {
// 獲取當前時時間戳 1466386762.345715 十位整數 6位小數NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
// 建立歌曲時間戳(後臺返回的時間 一般是13位數字)
NSTimeInterval createTime = [createTimeString longLongValue]/1000;
// 時間差
NSTimeInterval time = currentTime - createTime;
NSInteger sec = time/60;
if (sec<60) {
return [NSString stringWithFormat:@"%ld分鐘前",sec];
}
// 秒轉小時
NSInteger hours = time/3600;
if (hours<24) {
return [NSString stringWithFormat:@"%ld小時前",hours];
}
//秒轉天數
NSInteger days = time/3600/24;
if (days < 30) {
return [NSString stringWithFormat:@"%ld天前",days];
}
//秒轉月
NSInteger months = time/3600/24/30;
if (months < 12) {
return [NSString stringWithFormat:@"%ld月前",months];
}
//秒轉年
NSInteger years = time/3600/24/30/12;
return [NSString stringWithFormat:@"%ld年前",years];
}
附錄:如果後臺給的時間格式為:yyyy-MM-dd HH:mm:ss.SSS
+ (NSString *) compareCurrentTime:(NSString *)str
{
//把字串轉為NSdate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSDate *timeDate = [dateFormatter dateFromString:str];
//得到與當前時間差
NSTimeInterval timeInterval = [timeDate timeIntervalSinceNow];
timeInterval = -timeInterval;
//標準時間和北京時間差8個小時
timeInterval = timeInterval - 8*60*60;
long temp = 0;
NSString *result;
if (timeInterval < 60) {
result = [NSString stringWithFormat:@"剛剛"];
}
else if((temp = timeInterval/60) <60){
result = [NSString stringWithFormat:@"%d分鐘前",temp];
}
else if((temp = temp/60) <24){
result = [NSString stringWithFormat:@"%d小時前",temp];
}
else if((temp = temp/24) <30){
result = [NSString stringWithFormat:@"%d天前",temp];
}
else if((temp = temp/30) <12){
result = [NSString stringWithFormat:@"%d月前",temp];
}
else{
temp = temp/12;
result = [NSString stringWithFormat:@"%d年前",temp];
}
return result;
}