2010-01-09 46 views
5

基本上,我从API获取日期时间字符串,并且我想在应用程序中显示此活动在'5小时前'或'3天前'发生,依此类推...如何从一个NSDate对象的字符串获得一个时间?

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

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

回答

7

为此,使用NSCalendar要好得多。它专为这种转换而设计。

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

谢谢,这太好了! – akv 2010-01-10 02:06:49

+0

这样做的问题是,发生的事情,比方说,4天前会表示为“3天,14小时,6分钟”等。我建议使用这个答案从另一个问题:http:// stackoverflow.com/a/932130/591487 – inorganik 2014-07-29 18:27:29

相关问题