2012-11-20 55 views
1

我正在通過谷歌日曆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; 
} 

請幫助我,我曾試着改變日期格式很多次,但沒有成功。

+0

最簡單的做法是預處理字符串以刪除最後的「:」,然後使用時區使用「ZZZ」的香草格式字符串。然而,新的「ZZZZZ」應該適用於包含「:」的時間戳風格 - 我從來沒有嘗試過。 –

+1

請注意,上面的格式字符串在毫秒內缺少「SSS」 - 應該是像「」yyyy「 - 'MM' - 'dd'T'HH':'mm':'ss'。'SSSZZZZZ'' –

回答

0

的問題是,日期包含(-05:00)「:」在區值......你必須從刪除字符串然後上述方法將工作正常......新的日期字符串應該看起來像下面

2012-05-23T18:30:00.000-0500 - 這應該是正確的格式。

1

嘗試用這種方法..

-(NSDate *)convertStringToDate:(NSString *) date { 
     NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; 
     NSDate *nowDate = [[[NSDate alloc] init] autorelease]; 
     [formatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:ssZ"];// set format here which format in string date 
     /// also try this format @"yyyy-MM-dd'T'HH:mm:ss.fffK" 
     date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""]; 
     nowDate = [formatter dateFromString:date]; 
     // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate); 
     return nowDate; 
} 

調用此方法像波紋管..

NSDate *date = [self convertStringToDate:rfc3339DateTimeString]; 

也與一些RFC日期酸鹽用fffK此格式嘗試看到波紋管。鏈接..

how-do-i-parse-and-convert-datetimes-to-the-rfc-3339-date-time-format

我希望這個答案是有幫助的

+0

Nop,仍然沒有工作...當它調用[rfc3339DateFormatter dateFromString:rfc3339DateTimeString]它返回nil。我無法獲得日期對象... –

+0

@BharatJ試試這個編輯答案與我的方法,並嘗試其他rfc ffk格式,如果需要..我發佈的鏈接也ffk ..我希望你會得到解決方案這個問題交配.. –

相關問題