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作为标准,因此,

如果需要更精准的计算,把对应的一小段代码替换掉即可

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值