方式一 后臺給的格式為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;
}
方式二 后臺給的格式為 純數字1352170595000
(13位)
/** 通過行數, 返回更新時間 */
- (NSString *)updateTimeForRow:(NSInteger)row {
// 獲取當前時時間戳 1466386762.345715 十位整數 6位小數
NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
// 創建歌曲時間戳(后臺返回的時間 一般是13位數字)
NSTimeInterval createTime = self.model.tracks.list[row].createdAt/1000;
// 時間差
NSTimeInterval time = currentTime - createTime;
// 秒轉小時
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];
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。