如何将 rfc3399 格式化的日期字符串转换为 NSDate 对象



我正在通过谷歌日历网络服务获取 rfc3399 格式的日期字符串。我想将此字符串转换为 NSDate 对象,以便我可以将有关此的事件添加到本地日历中。我在Apple有关NSDateFormatter的文档中找到了以下方法,但它不起作用

日期字符串 - 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;
}

请帮助我,我已经尝试了很多次更改日期格式,但没有成功。

尝试使用此方法。

-(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 对于这种格式,请参阅此波纹管。

链接..

如何解析和转换日期时间到 RFC-3339 日期时间格式

我希望这个答案对您有所帮助

问题是日期在时区值中包含 (-05:00 )':' ...您必须将其从字符串中删除,然后上述方法就可以正常工作......新的日期字符串应如下所示

2012-05-23T18:30:00.000-0500 - 这应该是正确的格式。

最新更新