【问题标题】:Is there a popular method of displaying time since a unix timestamp?自unix时间戳以来是否有一种流行的显示时间的方法?
【发布时间】:2013-02-14 23:43:29
【问题描述】:

我已经用 PHP 完成了数百次,但现在我正在学习 xcode,但我无法弄清楚。我正在尝试在这样的 tableView 单元格上显示 Unix 时间戳 - >“10 分钟 24 秒前”、“4 小时、2 分钟前”或“2 天 4 小时前”。有什么想法吗?

【问题讨论】:

标签: objective-c cocoa-touch timestamp


【解决方案1】:

我遇到了同样的事情,这是我想出的 unix 时间戳:

-(NSString *)timeSinceNow:(float)timestamp{
NSMutableString *time = [[NSMutableString alloc]init];
NSTimeInterval ti = [[NSDate date] timeIntervalSince1970];
float diff = ti - timestamp;
//days
if (diff<60*60*24*365) {
    [time appendString:[NSString stringWithFormat:@"%d day", (int)floor(diff/(60*60*24))]];
}
//hours
if (diff<60*60*24) {
    [time appendString:[NSString stringWithFormat:@"%d hour", (int)floor(diff/(60*60))]];
}
//minutes
if (diff<60*60) {
    [time appendString:[NSString stringWithFormat:@"%d minute", (int)floor(diff/(60))]];
}
//seconds
if (diff<60) {
    [time appendString:[NSString stringWithFormat:@"%d second", (int)floor(diff)]];
}
//years
if (diff>=60*60*24*365) {
    [time appendString:[NSString stringWithFormat:@"%d year", (int)floor(diff/(60*60*24*365))]];
}
//check if its not singular (plural) - add 's' if so
if (![[time substringToIndex:2] isEqualToString:@"1 "]) {
    [time appendString:@"s"];
}
return time;
}

【讨论】:

    【解决方案2】:
    【解决方案3】:

    NSDate *now = [NSDate 日期];

    应该建立差异,然后将其绑定到单元格

    【讨论】:

      【解决方案4】:

      试试这个第三方库:https://github.com/billgarrison/SORelativeDateTransformer

      您可以通过 CocoaPods 安装它,或者使用 README 中的说明进行安装。

      如果您想推出自己的解决方案,您可以使用+[NSDate dateWithTimeIntervalSinceReferenceDate:] 获取距当前时间的秒数,传入当前时间的参考日期+[NSDate date]。通过使用适当的单位划分结果,您应该能够获得所需的粒度级别。

      SORelativeDateTransformer 更进一步,通过巧妙地使用-[NSBundle localizedStringForKey:value:table:] 实现本地化。

      【讨论】:

        猜你喜欢
        • 2010-10-30
        • 2019-07-14
        • 1970-01-01
        • 2012-08-21
        • 2011-03-23
        • 2017-08-17
        • 1970-01-01
        相关资源
        最近更新 更多