方法一后臺(tái)給的是yyyy-MM-dd HH:mm:ss.SSS
+ (NSString *)timeInfoWithDateString:(NSString *)dateString {
// 把日期字符串格式化為日期對(duì)象
NSDate *date = [NSDate dateFromString:dateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *curDate = [NSDate date];
NSTimeInterval time = -[date timeIntervalSinceDate:curDate];
int month = (int)([curDate getMonth] - [date getMonth]);
int year = (int)([curDate getYear] - [date getYear]);
int day = (int)([curDate getDay] - [date getDay]);
NSTimeInterval retTime = 1.0;
// 小于一小時(shí)
if (time < 3600) {
retTime = time / 60;
retTime = retTime <= 0.0 ? 1.0 : retTime;
return [NSString stringWithFormat:@"%.0f分鐘前", retTime];
}
// 小于一天养晋,也就是今天
else if (time < 33600 * 24) {
retTime = time / 3600;
retTime = retTime <= 0.0 ? 1.0 : retTime;
return [NSString stringWithFormat:@"%.0f小時(shí)前", retTime];
}
// 昨天
else if (time < 33600 * 224 * 2) {
return @"昨天";
}
// 第一個(gè)條件是同年姆泻,且相隔時(shí)間在一個(gè)月內(nèi)
// 第二個(gè)條件是隔年,對(duì)于隔年潜秋,只能是去年12月與今年1月這種情況
else if ((abs(year) == 0 && abs(month) <= 1)
|| (abs(year) == 1 && [curDate getMonth] == 1 && [date getMonth] == 12)) {
int retDay = 0;
// 同年
if (year == 0) {
// 同月
if (month == 0) {
retDay = day;
}
}
if (retDay <= 0) {
// 這里按月最大值來(lái)計(jì)算
// 獲取發(fā)布日期中峻呛,該月總共有多少天
int totalDays = [NSDate daysInMonth:(int)[date getMonth] year:(int)[date getYear]];
// 當(dāng)前天數(shù) + (發(fā)布日期月中的總天數(shù)-發(fā)布日期月中發(fā)布日,即等于距離今天的天數(shù))
retDay = (int)[curDate getDay] + (totalDays - (int)[date getDay]);
if (retDay >= totalDays) {
return [NSString stringWithFormat:@"%d個(gè)月前", (abs)(MAX(retDay / 31, 1))];
}
}
return [NSString stringWithFormat:@"%d天前", (abs)(retDay)];
} else {
if (abs(year) <= 1) {
if (year == 0) { // 同年
return [NSString stringWithFormat:@"%d個(gè)月前", abs(month)];
}
// 相差一年
int month = (int)[curDate getMonth];
int preMonth = (int)[date getMonth];
// 隔年所禀,但同月,就作為滿一年來(lái)計(jì)算
if (month == 12 && preMonth == 12) {
return @"1年前";
}
// 也不看颓屑,但非同月
return [NSString stringWithFormat:@"%d個(gè)月前", (abs)(12 - preMonth + month)];
}
return [NSString stringWithFormat:@"%d年前", abs(year)];
}
return @"1小時(shí)前";
}
方式二 后臺(tái)給的格式為 純數(shù)字23413423423
/** 通過(guò)行數(shù), 返回更新時(shí)間 */
- (NSString *)updateTimeForRow:(NSInteger)row {
// 獲取當(dāng)前時(shí)時(shí)間戳
NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
// 創(chuàng)建歌曲時(shí)間戳
NSTimeInterval createTime = self.model.tracks.list[row].createdAt/1000;
// 時(shí)間差
NSTimeInterval time = currentTime - createTime;
// 秒轉(zhuǎn)小時(shí)
NSInteger hours = time/3600;
if (hours<24) {
return [NSString stringWithFormat:@"%ld小時(shí)前",hours];
}
//秒轉(zhuǎn)天數(shù)
NSInteger days = time/3600/24;
if (days < 30) {
return [NSString stringWithFormat:@"%ld天前",days];
}
//秒轉(zhuǎn)月
NSInteger months = time/3600/24/30;
if (months < 12) {
return [NSString stringWithFormat:@"%ld月前",months];
}
//秒轉(zhuǎn)年
NSInteger years = time/3600/24/30/12;
return [NSString stringWithFormat:@"%ld年前",years];
}