【问题标题】:Smart Formatting of time span时间跨度的智能格式化
【发布时间】:2011-04-21 09:11:36
【问题描述】:

我需要一种方法将NSTimeInterval(以秒为单位的时间跨度)格式化为字符串,以生成类似 "about 10 minutes ago", "1h, 20min" em> 或 “不到 1 分钟”

-(NSString*) formattedTimeSpan:(NSTimeInterval)interval;

目标平台是 iOS。欢迎提供示例代码。

【问题讨论】:

标签: iphone objective-c time formatting


【解决方案1】:

这是 NSDate 的一个类别。它不完全使用 NSTimeInterval,内部很好:) 我假设您正在使用时间戳。

头文件 NSDate+PrettyDate.h

@interface NSDate (PrettyDate)

- (NSString *)prettyDate;

@end

实现 NSDate+PrettyDate.m

@implementation NSDate (PrettyDate)

- (NSString *)prettyDate
{
    NSString * prettyTimestamp;

    float delta = [self timeIntervalSinceNow] * -1;

    if (delta < 60) {
        prettyTimestamp = @"just now";
    } else if (delta < 120) {
        prettyTimestamp = @"one minute ago";
    } else if (delta < 3600) {
        prettyTimestamp = [NSString stringWithFormat:@"%d minutes ago", (int) floor(delta/60.0) ];
    } else if (delta < 7200) {
        prettyTimestamp = @"one hour ago";      
    } else if (delta < 86400) {
        prettyTimestamp = [NSString stringWithFormat:@"%d hours ago", (int) floor(delta/3600.0) ];
    } else if (delta < ( 86400 * 2 ) ) {
        prettyTimestamp = @"one day ago";       
    } else if (delta < ( 86400 * 7 ) ) {
        prettyTimestamp = [NSString stringWithFormat:@"%d days ago", (int) floor(delta/86400.0) ];
    } else {
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];

        prettyTimestamp = [NSString stringWithFormat:@"on %@", [formatter stringFromDate:self]];
        [formatter release];
    }

    return prettyTimestamp;
}

【讨论】:

  • 我相信我已经在 twitter 客户端的某个地方看到过该代码。这不完全是我需要的,但我可以使用它。我需要更精确的时间,比如 1 小时、20 分钟。
  • 我已经从一个用于社交网络应用程序的 javascript 库中移植了它。如果您需要更高的精度,您可以轻松添加更多区间块。只是作为一个想法。
  • ^是的,我从我在社交网站上使用的 JS 库中认识到这一点!看到它像这样在 Objective-C 中布局真是太酷了!
【解决方案2】:

您可能想参考 Facebook three20 框架。在他们的 NSDateAdditions 中,他们提供了一些漂亮的日期格式。它可能比你扩展它更好。

参考来源https://github.com/facebook/three20/blob/master/src/Three20Core/Sources/NSDateAdditions.m

- (NSString*)formatShortRelativeTime; 会给你“

【讨论】:

    【解决方案3】:

    这是一种以 Facebook 风格格式化日期的方法:

    https://github.com/nikilster/NSDate-Time-Ago

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      相关资源
      最近更新 更多