iPhone: Convert date string to a relative time stamp

后端 未结 11 1104
醉梦人生
醉梦人生 2020-11-27 09:30

I\'ve got a timestamp as a string like:

Thu, 21 May 09 19:10:09 -0700

and I\'d like to convert it to a relative time stamp like

11条回答
  •  难免孤独
    2020-11-27 10:09

    I can't edit yet, but I took Gilean's code and made a couple of tweaks and made it a category of NSDateFormatter.

    It accepts a format string so it will work w/ arbitrary strings and I added if clauses to have singular events be grammatically correct.

    Cheers,

    Carl C-M

    @interface NSDateFormatter (Extras)
    + (NSString *)dateDifferenceStringFromString:(NSString *)dateString
                                      withFormat:(NSString *)dateFormat;
    
    @end
    
    @implementation NSDateFormatter (Extras)
    
    + (NSString *)dateDifferenceStringFromString:(NSString *)dateString
                                      withFormat:(NSString *)dateFormat
    {
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
      [dateFormatter setDateFormat:dateFormat];
      NSDate *date = [dateFormatter dateFromString:dateString];
      [dateFormatter release];
      NSDate *now = [NSDate date];
      double time = [date timeIntervalSinceDate:now];
      time *= -1;
      if(time < 1) {
        return dateString;
      } else if (time < 60) {
        return @"less than a minute ago";
      } else if (time < 3600) {
        int diff = round(time / 60);
        if (diff == 1) 
          return [NSString stringWithFormat:@"1 minute ago", diff];
        return [NSString stringWithFormat:@"%d minutes ago", diff];
      } else if (time < 86400) {
        int diff = round(time / 60 / 60);
        if (diff == 1)
          return [NSString stringWithFormat:@"1 hour ago", diff];
        return [NSString stringWithFormat:@"%d hours ago", diff];
      } else if (time < 604800) {
        int diff = round(time / 60 / 60 / 24);
        if (diff == 1) 
          return [NSString stringWithFormat:@"yesterday", diff];
        if (diff == 7) 
          return [NSString stringWithFormat:@"last week", diff];
        return[NSString stringWithFormat:@"%d days ago", diff];
      } else {
        int diff = round(time / 60 / 60 / 24 / 7);
        if (diff == 1)
          return [NSString stringWithFormat:@"last week", diff];
        return [NSString stringWithFormat:@"%d weeks ago", diff];
      }   
    }
    
    @end
    

提交回复
热议问题