【问题标题】:How to get a time since string from a NSDate object?如何从 NSDate 对象中获取自字符串以来的时间?
【发布时间】:2010-01-09 18:57:32
【问题描述】:

基本上,我从 API 获取日期时间字符串,并且我想在应用程序中显示此活动发生在“5 小时前”或“3 天前”等...

我目前正在尝试从 [NSDate timeIntervalSinceNow] 方法获取 NSTimeInterval。然后使用[NSDate dateWithTimeIntervalSince1970:interval] 再次将时间间隔转换为 NSDate。然后检查间隔,看看它是否小于 60/3600/86400/等,为输出 NSDateFormatter 对象设置正确的格式。

这是正确的做法吗?还是有更简单/更好的方法来做到这一点?

【问题讨论】:

    标签: iphone cocoa datetime format


    【解决方案1】:

    为此使用NSCalendar 会更好。它是为这种转换而设计的。

    NSUInteger desiredComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSDayCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *elapsedTimeUnits = [[NSCalendar currentCalendar] components:desiredComponents 
                                                                       fromDate:activityDate 
                                                                       toDate:[NSDate date] 
                                                                       options:0];
    

    【讨论】:

    • 这样做的问题是,4天前发生的事情将被表示为“3天,14小时,6分钟”等。我建议使用这个答案另一个问题:stackoverflow.com/a/932130/591487
    【解决方案2】:

    查看这个项目:https://github.com/kevinlawler/NSDate-TimeAgo

    这是 NSDate 的一个类别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 2016-09-04
      • 2015-03-04
      • 2018-12-27
      • 2023-03-18
      • 2016-07-24
      • 1970-01-01
      相关资源
      最近更新 更多