1. 程式人生 > >iOS常用於顯示幾小時前/幾天前/幾月前/幾年前的程式碼片段

iOS常用於顯示幾小時前/幾天前/幾月前/幾年前的程式碼片段

/**
 * Retain a formated string with a real date string
 *
 * @param dateString a real date string, which can be converted to a NSDate object
 *
 * @return a string that will be x分鐘前/x小時前/昨天/x天前/x個月前/x年前
 */
+ (NSString *)timeInfoWithDateString:(NSString *)dateString {
  // 把日期字串格式化為日期物件
  NSDate *date = [NSDate dateFromString:dateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
  
  NSDate *curDate = [NSDate date];
  NSTimeInterval time = -[date timeIntervalSinceDate:curDate];
  
  int month = (int)([curDate getMonth] - [date getMonth]);
  int year = (int)([curDate getYear] - [date getYear]);
  int day = (int)([curDate getDay] - [date getDay]);
  
  NSTimeInterval retTime = 1.0;
  // 小於一小時
  if (time < 3600) {
    retTime = time / 60;
    retTime = retTime <= 0.0 ? 1.0 : retTime;
    return [NSString stringWithFormat:@"%.0f分鐘前", retTime];
  }
  // 小於一天,也就是今天
  else if (time < 3600 * 24) {
    retTime = time / 3600;
    retTime = retTime <= 0.0 ? 1.0 : retTime;
    return [NSString stringWithFormat:@"%.0f小時前", retTime];
  }
  // 昨天
  else if (time < 3600 * 24 * 2) {
    return @"昨天";
  }
  // 第一個條件是同年,且相隔時間在一個月內
  // 第二個條件是隔年,對於隔年,只能是去年12月與今年1月這種情況
  else if ((abs(year) == 0 && abs(month) <= 1)
           || (abs(year) == 1 && [curDate getMonth] == 1 && [date getMonth] == 12)) {
    int retDay = 0;
    // 同年
    if (year == 0) {
      // 同月
      if (month == 0) {
        retDay = day;
      }
    }
    
    if (retDay <= 0) {
      // 這裡按月最大值來計算
      // 獲取釋出日期中,該月總共有多少天
      int totalDays = [NSDate daysInMonth:(int)[date getMonth] year:(int)[date getYear]];
      // 當前天數 + (釋出日期月中的總天數-釋出日期月中釋出日,即等於距離今天的天數)
      retDay = (int)[curDate getDay] + (totalDays - (int)[date getDay]);
      
      if (retDay >= totalDays) {
        return [NSString stringWithFormat:@"%d個月前", (abs)(MAX(retDay / 31, 1))];
      }
    }
    
    return [NSString stringWithFormat:@"%d天前", (abs)(retDay)];
  } else  {
    if (abs(year) <= 1) {
      if (year == 0) { // 同年
        return [NSString stringWithFormat:@"%d個月前", abs(month)];
      }
      
      // 相差一年
      int month = (int)[curDate getMonth];
      int preMonth = (int)[date getMonth];
      
      // 隔年,但同月,就作為滿一年來計算
      if (month == 12 && preMonth == 12) {
        return @"1年前";
      }
      
      // 也不看,但非同月
      return [NSString stringWithFormat:@"%d個月前", (abs)(12 - preMonth + month)];
    }
    
    return [NSString stringWithFormat:@"%d年前", abs(year)];
  }
  
  return @"1小時前";
}

這裡計算多少個月前時,為了減少計算量,沒有分別獲取對應月份的總天數,而是使用月份最大值31作為標準,因此,

如果需要更精準的計算,把對應的一小段程式碼替換掉即可