如何将人们可读的字符串显示为“10秒前”或“3小时前”?

时间:2013-01-16 13:00:14

标签: iphone ios objective-c ipad

  

可能重复:
  Getting human readable relative times and dates from a unix timestamp?

我所拥有的只是过去的NSTimeInterval。如何将其转换为“humanly readable”字符串,例如“10 seconds ago”或“3 hours ago”?

2 个答案:

答案 0 :(得分:2)

NSTimeInterval为您提供秒数。

确认秒后,您可以使用%和/来查找天,小时,分钟和秒。

参见此演示:

NSInteger seconds = totalSecondsSinceStart % 60;
NSInteger minutes = (totalSecondsSinceStart / 60) % 60;
NSInteger hours = totalSecondsSinceStart / (60 * 60);
NSString *result = NSString stringWithFormat:@"%02ld hour %02ld minutues %02ld seconds ago", hours, minutes, seconds];

输出将如下:

01 hours 34 minutes 49 seconds ago

答案 1 :(得分:0)

格式化程度更高,因此您看不到0小时0分34秒。

+(NSString *)returnRelativeTime:(NSString *)dateString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate *date = [formatter dateFromString:dateString];
    int timeSince = [date timeIntervalSinceNow] * -1;

    int days    = (timeSince / (3600 * 24));
    int hours   = (timeSince / 3600)- (days *24);
    int minutes = (timeSince % 3600) / 60;
//    int seconds = (timeSince % 3600) %  60;
//    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours ,minutes, seconds];
    if (days >0) {
         return [NSString stringWithFormat:@"%01d days %01d hours ago",days, hours];
    }
    else if (hours == 0) {
        return [NSString stringWithFormat:@"%01dm ago", minutes];
    }
    else {
        return [NSString stringWithFormat:@"%01dh %01dm ago", hours ,minutes];
    }

}