github地址: https://github.com/neobug/timeFormatter
時(shí)間格式化 根據(jù)上傳的時(shí)間戳對(duì)應(yīng)的字符串,
跟當(dāng)前時(shí)間做對(duì)比, 24小時(shí)內(nèi)顯示 : xx小時(shí)前/xx分鐘前/剛剛.
24小時(shí)-48小時(shí)顯示:昨天.
48小時(shí)-72小時(shí)顯示:前天
超過(guò)72小時(shí)顯示對(duì)應(yīng)日期 和 時(shí)間: 2016-04-05 13:23
- (void)viewDidLoad {
[super viewDidLoad];
// NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// //設(shè)定時(shí)間格式,這里可以設(shè)置成自己需要的格式
// [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
// //輸出格式為:2010-10-27 10:22:13
// NSLog(@"%@",currentDateStr);
NSDate *datenow = [NSDate date];
NSString *s2 = [NSString stringWithFormat:@"%.f",[datenow timeIntervalSince1970] - 60*60*48];
NSLog(@"~~~~%@",s2);
NSString *s = [self timeContrast:s2];//@"1459406857"];
NSLog(@"s = %@",s);
}
//輸入時(shí)間戳 對(duì)應(yīng)的字符串 如:1459406857; 返回對(duì)應(yīng)格式的時(shí)間(跟當(dāng)前時(shí)間做對(duì)比)
- (NSString *)timeContrast:(NSString *)update_at {
//獲取當(dāng)前時(shí)間
NSDate *dateNow = [NSDate date];
NSString *timeStampNow = [NSString stringWithFormat:@"%.f",[dateNow timeIntervalSince1970]];
float time = (float)([timeStampNow intValue] - [update_at longLongValue]/1000);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//設(shè)定時(shí)間格式,這里可以設(shè)置成自己需要的格式
NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:[update_at doubleValue]/1000];
[dateFormatter setDateFormat:@"MM"];
NSString * nowDay1 = [dateFormatter stringFromDate:[NSDate date]];
NSString * lastDay1 = [dateFormatter stringFromDate:beDate];
[dateFormatter setDateFormat:@"dd"];
NSString * nowDay = [dateFormatter stringFromDate:[NSDate date]];
NSString * lastDay = [dateFormatter stringFromDate:beDate];
[dateFormatter setDateFormat:@"HH:mm"];
NSString *s = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[update_at longLongValue]/1000]]];
if (time/3600 <24.0) {
if (time/60 < 1.0){
s = [NSString stringWithFormat:@"剛剛"];
}else if (time/60<60 && time/60 >= 1.0) {
float minute = time/60;
s = [NSString stringWithFormat:@"%.f分鐘前",minute];
}else if (time/60 >=60 && [nowDay intValue] == [lastDay intValue]) {
s = [NSString stringWithFormat:@"今天 %@",s];
}
}else if ( ([nowDay intValue] - [lastDay intValue] == 1) && [nowDay1 intValue] == [lastDay1 intValue]) {
s = [NSString stringWithFormat:@"昨天 %@",s];
}else if (([nowDay intValue] - [lastDay intValue] == 2) && [nowDay1 intValue] == [lastDay1 intValue]) {
s = [NSString stringWithFormat:@"前天 %@",s];
}else {
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
s = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[update_at longLongValue]/1000]]];
}
return s;
}
注意:返回的 update_at時(shí)間戳 是否是多少位,如果包含后面3個(gè)0,需要用 [update_at longlongValue]
且 要 [update_at longlongValue] / 1000 .