github地址: https://github.com/neobug/timeFormatter
时间格式化 根据上传的时间戳对应的字符串,
跟当前时间做对比, 24小时内显示 : xx小时前/xx分钟前/刚刚.
24小时-48小时显示:昨天.
48小时-72小时显示:前天
超过72小时显示对应日期 和 时间: 2016-04-05 13:23
- (void)viewDidLoad {
[super viewDidLoad];
// NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// //设定时间格式,这里可以设置成自己需要的格式
// [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);
}
//输入时间戳 对应的字符串 如:1459406857; 返回对应格式的时间(跟当前时间做对比)
- (NSString *)timeContrast:(NSString *)update_at {
//获取当前时间
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];
//设定时间格式,这里可以设置成自己需要的格式
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时间戳 是否是多少位,如果包含后面3个0,需要用 [update_at longlongValue]
且 要 [update_at longlongValue] / 1000 .