user200341
user200341

Reputation: 253

How do you convert date time including milliseconds and timezone info to NSDate

I'm trying to convert a string to an NSDate, however the format always comes out as nil

The date I'm trying to convert is:

2012-08-16T16:20:52.619000+00:00

The date format I'm trying is:

@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZ"

If I change the date to:

@"2012-08-16T16:20:52.619000+0000" // removing the : from +00:00

it works a treat, however I would

(I have also tried

@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZ:ZZ" 
@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZ':'ZZ" 

but that didn't work either).

Is it even possible to do this without doing string manipulation and removing the final ":"?

Upvotes: 1

Views: 3148

Answers (3)

J2theC
J2theC

Reputation: 4452

It looks like you are using ISO 8601 formatted dates. If you are getting these from a web service, the format changes according to the format. Check this out:

http://boredzo.org/iso8601parser/

This will convert dates according to the format, and even when the format changes slightly.

Upvotes: 1

Tom Fobear
Tom Fobear

Reputation: 6749

How about something like

[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

the Z has to be in single quotes.

Upvotes: -1

user200341
user200341

Reputation: 253

I did a final search around this and found out that you have to use

getObjectValue

rather than

dateFromString

In case someone else runs in to this issue, I post my method for converting such strings to NSDate

+ (NSDate *)dateFromString:(NSString *)dateString {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"];

    NSDate *theDate = nil;
    NSError *error = nil;
    [dateFormat getObjectValue:&theDate forString:dateString range:nil error:&error];
    [dateFormat release];
    return theDate;
}

Upvotes: 4

Related Questions