iOS根据日期判断是刚刚、几分钟前、几小时前等的代码片段

来源:互联网 发布:linux 系统 死机 日志 编辑:程序博客网 时间:2024/04/30 06:21
  1. 是NSDate的一个扩展方法:
  2. - (NSString *)prettyDateWithReference:(NSDate *)reference {  
  3.   NSString *suffix = @"ago";  
  4.     
  5.   float different = [reference timeIntervalSinceDate:self];  
  6.   if (different < 0) {  
  7.     different = -different;  
  8.     suffix = @"from now";  
  9.   }  
  10.     
  11.   // days = different / (24 * 60 * 60), take the floor value  
  12.   float dayDifferent = floor(different / 86400);  
  13.     
  14.   int days   = (int)dayDifferent;  
  15.   int weeks  = (int)ceil(dayDifferent / 7);  
  16.   int months = (int)ceil(dayDifferent / 30);  
  17.   int years  = (int)ceil(dayDifferent / 365);  
  18.     
  19.   // It belongs to today  
  20.   if (dayDifferent <= 0) {  
  21.     // lower than 60 seconds  
  22.     if (different < 60) {  
  23.       return @"just now";  
  24.     }  
  25.       
  26.     // lower than 120 seconds => one minute and lower than 60 seconds  
  27.     if (different < 120) {  
  28.       return [NSString stringWithFormat:@"1 minute %@", suffix];  
  29.     }  
  30.       
  31.     // lower than 60 minutes  
  32.     if (different < 660 * 60) {  
  33.       return [NSString stringWithFormat:@"%d minutes %@", (int)floor(different / 60), suffix];  
  34.     }  
  35.       
  36.     // lower than 60 * 2 minutes => one hour and lower than 60 minutes  
  37.     if (different < 7200) {  
  38.       return [NSString stringWithFormat:@"1 hour %@", suffix];  
  39.     }  
  40.       
  41.     // lower than one day  
  42.     if (different < 86400) {  
  43.       return [NSString stringWithFormat:@"%d hours %@", (int)floor(different / 3600), suffix];  
  44.     }  
  45.   }  
  46.   // lower than one week  
  47.   else if (days < 7) {  
  48.     return [NSString stringWithFormat:@"%d day%@ %@", days, days == 1 ? @"" : @"s", suffix];  
  49.   }  
  50.   // lager than one week but lower than a month  
  51.   else if (weeks < 4) {  
  52.     return [NSString stringWithFormat:@"%d week%@ %@", weeks, weeks == 1 ? @"" : @"s", suffix];  
  53.   }  
  54.   // lager than a month and lower than a year  
  55.   else if (months < 12) {  
  56.     return [NSString stringWithFormat:@"%d month%@ %@", months, months == 1 ? @"" : @"s", suffix];  
  57.   }  
  58.   // lager than a year  
  59.   else {  
  60.     return [NSString stringWithFormat:@"%d year%@ %@", years, years == 1 ? @"" : @"s", suffix];  
  61.   }  
  62.     
  63.   return self.description;  
  64. }  
0 0
原创粉丝点击