2012-01-16 121 views
4

Youtube API以RFC3339格式返回日期字符串。我發現如何在手冊上解析它,無論如何,這太長了。在iOS中解析RFC3339日期字符串的最簡單方法是什麼?

- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString 
    // Returns a user-visible date time string that corresponds to the 
    // specified RFC 3339 date time string. Note that this does not handle 
    // all possible RFC 3339 date time strings, just one of the most common 
    // styles. 
{ 
    NSString *   userVisibleDateTimeString; 
    NSDateFormatter * rfc3339DateFormatter; 
    NSLocale *   enUSPOSIXLocale; 
    NSDate *   date; 
    NSDateFormatter * userVisibleDateFormatter; 

    userVisibleDateTimeString = nil; 

    // Convert the RFC 3339 date time string to an NSDate. 

    rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 

    enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 

    [rfc3339DateFormatter setLocale:enUSPOSIXLocale]; 
    [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; 
    [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

    date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString]; 
    if (date != nil) { 

     // Convert the NSDate to a user-visible date string. 

     userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
     assert(userVisibleDateFormatter != nil); 

     [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle]; 
     [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle]; 

     userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date]; 
    } 
    return userVisibleDateTimeString; 
} 

我可以做一個函數包含這一點,但我想知道的是可可基金會或標準C或POSIX庫有預先定義的方式來做到這一點。如果有的話,我想使用它。你能讓我知道有沒有更簡單的方法?或者,如果您確認這是最簡單的方式,將是非常感謝:)

回答

2

純粹的東西,帶來可可方式正是你在做什麼。您可以通過在其他地方創建日期格式化程序來縮短和加快此方法,可能在init中,並在此方法中使用/重複使用它們。

+0

不幸的是,當我測試一次時,此代碼無法處理秒數的派系部分...... – Eonil 2012-01-17 02:50:20

+0

@Eonil:您需要修改格式字符串。在相關規範中定義了小數秒的格式字符:http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns – 2012-01-17 03:30:36

+0

哦,這看起來不錯。我會試試這個:) – Eonil 2012-01-17 03:50:02

1

我在解析Obj-c中的RFC 3339時遇到了一些問題,因爲小數秒和區域似乎是可選的。

最可靠的功能,我發現這是吉斯特(其中我不是作家):https://gist.github.com/mwaterfall/953664

2

您需要兩種格式,因爲分數秒是可選的,和時區應該是Z5,而不是Z.因此,你創建兩個格式化格式

@"yyyy'-'MM'-'dd'T'HH':'mm':'ssX5" 
@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSSSX5" 

並嘗試它們兩個。這顯然是RFC3339;您的字符串可能不是這種格式。很高興你沒有要求RFC822,這是一個很難做到的事情。但是你應該首先返回一個返回NSDate的方法,因爲大多數用途實際上並不需要爲用戶格式化的字符串。

相關問題