2010-01-04 56 views
10

是否有一種簡單的方法將您從Twitter獲得的時間戳轉換爲unix時間或分鐘數?我可以通過字符串解析並自行轉換所有內容,但我希望有一種方法可以將其轉換爲不需要的。這是帶有時間戳的created_at元素的示例。iPhone + Twitter API:轉換時間?

太陽03月18日6時42分26秒+0000 2007

回答

22

您可以使用NSDateFormatter像這樣的東西:


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[dateFormatter setLocale:usLocale]; 
[usLocale release]; 
[dateFormatter setDateStyle:NSDateFormatterLongStyle]; 
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 

// see http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns 
[dateFormatter setDateFormat: @"EEE MMM dd HH:mm:ss Z yyyy"]; 

NSDate *date = [dateFormatter dateFromString:[currentDict objectForKey:@"created_at"]]; 
[dateFormatter release]; 

NSTimeInterval seconds = [date timeIntervalSince1970]; 
+0

謝謝,完美無缺! – self 2012-07-14 08:29:28

+2

這也是部分錯誤! NSDateFormatter對象的創建非常繁重,因此請將其設置爲靜態,或儘可能使其成爲ivar。 – 2012-07-14 21:14:58

0

文件與蘋果的功能請求,讓他們知道你想要在iPhone上這個功能。 NSDateFormatter提供了一個傳統的初始化方法,其布爾標誌表示您希望它解析自然語言,但它只能在OS X上使用。Wil Shipley在啓發式和人爲因素的背景下回寫了這個功能,然後寫了一個interesting post

這似乎並不可能,蘋果將提供此功能,因爲這記將從NSDateFormatter docs表示:

iPhone OS注:iPhone OS支持 只有10.4+行爲。在iPhone OS上可用的10.0式 方法和格式字符串不是 。

換句話說,我認爲你必須自己解析它。

2

我一直在這個整天strugeling,但這個線程幫助我找到一個解決方案。

這是我如何將Twitter「created_at」屬性轉換爲NSDATE;

NSDateFormatter *fromTwitter = [[NSDateFormatter alloc] init]; 
// here we set the DateFormat - note the quotes around +0000 
[fromTwitter setDateFormat:@"EEE MMM dd HH:mm:ss '+0000' yyyy"]; 
// We need to set the locale to english - since the day- and month-names are in english 
[fromTwitter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]]; 

NSString *dateString = [item objectForKey:@"created_at"]; 
NSDate *tweetedDate = [fromTwitter dateFromString:dateString]; 

我希望有人會覺得這有幫助。

+0

ZOMG謝謝你的作品!發現5個其他格式無效。關鍵似乎是其他人似乎錯過的地方。 – 2013-10-17 10:36:50