2010-01-09 66 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

相關問題