我正在通過谷歌日曆Web服務獲取rfc3399格式的日期字符串。我想將此字符串轉換爲NSDate對象,以便我可以將關於此事件的事件添加到本地日曆中。我發現蘋果的文檔在下面的方法就NSDateFormatter,但其沒有工作iphone - 如何將rfc3399格式的日期字符串轉換爲NSDate對象?
日期字符串 - 2012-05-23T18:30:00.000-05:00
- (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.
*/
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
NSString *userVisibleDateTimeString;
if (date != nil) {
// Convert the date object to a user-visible date string.
NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];
assert(userVisibleDateFormatter != nil);
[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
[userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}
return userVisibleDateTimeString;
}
請幫助我,我曾試着改變日期格式很多次,但沒有成功。
最簡單的做法是預處理字符串以刪除最後的「:」,然後使用時區使用「ZZZ」的香草格式字符串。然而,新的「ZZZZZ」應該適用於包含「:」的時間戳風格 - 我從來沒有嘗試過。 –
請注意,上面的格式字符串在毫秒內缺少「SSS」 - 應該是像「」yyyy「 - 'MM' - 'dd'T'HH':'mm':'ss'。'SSSZZZZZ'' –