iOS开发-显示发送时间(几分钟前,几小时前,几天前)

来源:互联网 发布:中文翻译越南语软件 编辑:程序博客网 时间:2024/05/02 09:02
view plain copy
 print?
  1. //方式一 后台给的格式为yyyy-MM-dd HH:mm:ss.SSS  
  2. - (NSString *) compareCurrentTime:(NSString *)str  
  3. {  
  4.     //把字符串转为NSdate  
  5.     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
  6.     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  
  7.     NSDate *timeDate = [dateFormatter dateFromString:str];  
  8.     NSDate *currentDate = [NSDate date];  
  9.       
  10.     //得到两个时间差  
  11.     NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:timeDate];  
  12.     long temp = 0;  
  13.     NSString *result;  
  14.     if (timeInterval/60 < 1)  
  15.     {  
  16.         result = [NSString stringWithFormat:@"刚刚"];  
  17.     }  
  18.     else if((temp = timeInterval/60) <60){  
  19.         result = [NSString stringWithFormat:@"%ld分钟前",temp];  
  20.     }  
  21.     else if((temp = temp/60) <24){  
  22.         result = [NSString stringWithFormat:@"%ld小时前",temp];  
  23.     }  
  24.     else if((temp = temp/24) <30){  
  25.         result = [NSString stringWithFormat:@"%ld天前",temp];  
  26.     }  
  27.     else if((temp = temp/30) <12){  
  28.         result = [NSString stringWithFormat:@"%ld月前",temp];  
  29.     } else{  
  30.         temp = temp/12;  
  31.         result = [NSString stringWithFormat:@"%ld年前",temp];  
  32.     }  
  33.     return  result;  
  34. }  

[html]view plain copy
 print?
  1. //方式二 后台给的格式为 纯数字1352170595000(13位)  
  2. - (NSString *)updateTimeForRow:(NSString *)str {  
  3.     // 获取当前时时间戳 1466386762.345715 十位整数 6位小数  
  4.     NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];  
  5.     // 创建歌曲时间戳(后台返回的时间 一般是13位数字)  
  6.     NSTimeInterval createTime =[str floatValue]/1000;  
  7.     // 时间差  
  8.     NSTimeInterval time = currentTime - createTime;  
  9.       
  10.     //秒转分钟  
  11.     NSInteger small = time / 60;  
  12.     if (small == 0) {  
  13.         return [NSString stringWithFormat:@"刚刚"];  
  14.     }  
  15.       
  16.       
  17.     if (small < 60) {  
  18.         return [NSString stringWithFormat:@"%ld分钟前",small];  
  19.     }  
  20.       
  21.     // 秒转小时  
  22.     NSInteger hours = time/3600;  
  23.     if (hours<24) {  
  24.         return [NSString stringWithFormat:@"%ld小时前",hours];  
  25.     }  
  26.     //秒转天数  
  27.     NSInteger days = time/3600/24;  
  28.     if (days < 30) {  
  29.         return [NSString stringWithFormat:@"%ld天前",days];  
  30.     }  
  31.     //秒转月  
  32.     NSInteger months = time/3600/24/30;  
  33.     if (months < 12) {  
  34.         return [NSString stringWithFormat:@"%ld月前",months];  
  35.     }  
  36.     //秒转年  
  37.     NSInteger years = time/3600/24/30/12;  
  38.     return [NSString stringWithFormat:@"%ld年前",years];  
  39. }  

0 0
原创粉丝点击