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庫有預先定義的方式來做到這一點。如果有的話,我想使用它。你能讓我知道有沒有更簡單的方法?或者,如果您確認這是最簡單的方式,將是非常感謝:)
不幸的是,當我測試一次時,此代碼無法處理秒數的派系部分...... – Eonil 2012-01-17 02:50:20
@Eonil:您需要修改格式字符串。在相關規範中定義了小數秒的格式字符:http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns – 2012-01-17 03:30:36
哦,這看起來不錯。我會試試這個:) – Eonil 2012-01-17 03:50:02