前言
本文实现的效果类似于QQ空间里的好友发表的动态,会显示好友发表的时间,这里是处理显示几小时前,几分钟前,刚刚,昨天,前天这样的格式,下面来一起看看吧。
一:刚刚,几分钟前,几小时前
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//时间 NSString *createdTimeStr = @ "2017-01-01 21:05:10" ; //把字符串转为NSdate NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@ "yyyy-MM-dd HH:mm:ss" ]; NSDate *timeDate = [dateFormatter dateFromString:createdTimeStr]; //得到与当前时间差 NSTimeInterval timeInterval = [timeDate timeIntervalSinceNow]; timeInterval = -timeInterval; long temp = 0 ; NSString *result; if (timeInterval < 60 ) { result = [NSString stringWithFormat:@ "刚刚" ]; } else if ((temp = timeInterval/ 60 ) < 60 ){ result = [NSString stringWithFormat:@ "%ld分钟前" ,temp]; } else if ((temp = timeInterval/ 3600 ) > 1 && (temp = timeInterval/ 3600 ) < 24 ){ result = [NSString stringWithFormat:@ "%ld小时前" ,temp]; } else { result = createdTimeStr; } NSLog(@ "%@" ,result); |
二:刚刚,几分钟前,几小时前,昨天,前天
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
//时间 NSString *createdTimeStr = @ "2017-01-01 21:05:10" ; //把字符串转为NSdate NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@ "yyyy-MM-dd HH:mm:ss" ]; NSDate *timeDate = [dateFormatter dateFromString:createdTimeStr]; //得到与当前时间差 NSTimeInterval timeInterval = [timeDate timeIntervalSinceNow]; timeInterval = -timeInterval; long temp = 0 ; NSString *result; if (timeInterval < 60 ) { result = [NSString stringWithFormat:@ "刚刚" ]; } else if ((temp = timeInterval/ 60 ) < 60 ){ result = [NSString stringWithFormat:@ "%ld分钟前" ,temp]; } else if ((temp = timeInterval/ 3600 ) > 1 && (temp = timeInterval/ 3600 ) < 24 ){ result = [NSString stringWithFormat:@ "%ld小时前" ,temp]; } else if ((temp = timeInterval/ 3600 ) > 24 && (temp = timeInterval/ 3600 ) < 48 ){ result = [NSString stringWithFormat:@ "昨天" ]; } else if ((temp = timeInterval/ 3600 ) > 48 && (temp = timeInterval/ 3600 ) < 72 ){ result = [NSString stringWithFormat:@ "前天" ]; } else { result = createdTimeStr; } NSLog(@ "%@" ,result); |
总结
以上就是这篇文字的全部内容了,希望本文的内容对各位iOS开发者能带来一定的帮助,如果有疑问大家可以留言交流。
原文链接:http://blog.it985.com/19220.html