iphone - 时间跨度的智能格式化

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

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

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

最佳答案

这是 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;
}

https://stackoverflow.com/questions/5741952/

相关文章:

wpf - 使用小数分隔符格式化 XAML 中的值?

python - 在 Python 中使用 LaTeX 表示法格式化数字

formatting - 在 Redmine wiki 页面中插入特殊字符

c# - 使用 .NET 格式化大数

latex - 如何在 LaTeX 中的空格后设置制表位?

php - 正则表达式 - 去除非数字并删除美分(如果有)

java - 格式字符串变为 xxx1、xx10 或 1###、10## 等

javascript - jQuery 如何继续 Javascript 到新行?

c# - 为什么只有一个语句的方法需要大括号?

string - 如何在 Haskell 中填充整数的字符串表示形式?