如何将格式的NSString(2013-07-25T06:15:33.180-04:00)转换为NSDate?

时间:2013-07-24 10:25:54

标签: iphone ios nsdate nsdateformatter

如何将格式的NSString(2013-07-25T06:15:33.180-04:00)转换为NSDate?

我正在尝试使用以下代码进行转换

NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss ZZZ"];

    NSDate *theDate = nil;
    NSError *error = nil;
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
    }
    NSString *strDate = [rfc3339TimestampFormatterWithTimeZone stringFromDate:theDate];
    return strDate;

请帮帮我

1 个答案:

答案 0 :(得分:2)

尝试这样,我希望你会成功..

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"];
    NSDate *date = [dateFormatter dateFromString:@"2013-07-25T06:15:33.180-04:00"];//chnage symbal here.
    NSLog(@"%@",date);