-2

I am trying to parse

2013-01-23T22:46:29.564Z

into an NSDate with:

NSDate *date = [GeneralHelper getDateFromDateString:expiryDateASStr];
if(date != nil) {
    printf("\n PARSED DATE %s", [date.description UTF8String]);
} else {
    printf("\n failed to parse");
}

but it is failing, how can I get this to work? Thanks!

2
  • what's the .564Z part in your date? Jan 22, 2013 at 23:00
  • 3
    Could you post the code for getDateFromDateString? It's tough to tell whats wrong without seeing the code thats isn't working. Jan 22, 2013 at 23:00

2 Answers 2

4

Use a NSDateFormatter

NSString * dateString = @"2013-01-23T22:46:29.564Z";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:SS.SSS'Z'"];
NSDate * date = [dateFormatter dateFromString:dateString];
4

Like @Gabriele said, using a NSDateFormatter is the way to go. The following will work for you, including the date format:

NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setLocale:[NSLocale currentLocale]];
[df setCalendar:[NSCalendar currentCalendar]];
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:SS.SSS'Z'"];
NSLog(@"%@", [df dateFromString:expiryDateASStr]);

Do NOT use the capital Ys "YYYY" unless you want the year in "Week of Year" based calendars. Most use cases "yyyy" is the correct way to specify the year.

1
  • thanks I updated my answer, with a proper date format. You're right about the YYYY, I mistyped that. Also I didn't figure out that .464 were milliseconds, I was thinking about some kind of weird timezone! Jan 22, 2013 at 23:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.