該構造方法將時間戳記轉換為幾分鐘前/幾小時前/幾天前/幾年前
//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;}