views:

502

answers:

3

If I use the following code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];   
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm"];
NSDate *myDate = [dateFormatter dateFromString:@"2010-01-28T15:22:23.863"];
NSLog(@"%@", [dateFormatter stringFromDate:myDate]);

It is successfully converted to a Date object, however, I cannot seem to format it any other way than yyyy-MM-dd'T'HH:mm, i.e. what gets logged is 2010-01-28T15:22:23

If I change the dateFormat to say [dateFormatter setDateFormat:@"yyyy-MMMM-d'T'HH:mm"]; the Date object is null...

So my ultimate question is how to format an ISO8601 timestamp from a SQL database to use, for instance, NSDateFormatterMediumStyle to return "January 1, 2010"?

+1  A: 

You need another formatter to handle the output. Put this after your code:

NSDateFormatter *anotherDateFormatter = [[NSDateFormatter alloc] init];   
[anotherDateFormatter setDateStyle:NSDateFormatterLongStyle];
[anotherDateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSLog(@"%@", [anotherDateFormatter stringFromDate:myDate]);
osteven
+1  A: 

I should note that last time I checked Apples NSDate methods didn't support ISO8601. I still have a bug with Apple about putting official support in. + (id)dateWithNaturalLanguageString:(NSString *)string will properly (last time I ran it) parse and create an NSDate object from an ISO801 string, though the documentation says you shouldn't use it, it's worked on all ISO8601 dates I've tried so far.

Colin Wheeler
It's true that ` + (id)dateWithNaturalLanguageString:(NSString *)string` will parse successfully unless there are millis on your ISO8601 string.
John Wright
+1  A: 

I have a similiar but slightly more complex problem, and I've found a very simple solution!

The problem: My incoming ISO8601 dates look like this: 2006-06-14T11:06:00+02:00 They have a timezone offset at the end.

The solution: Use Peter Hosey's ISO8601DateFormatter which you can download from here.

ISO8601DateFormatter *formatter = [[ISO8601DateFormatter alloc] init];
NSDate *theDate = [formatter dateFromString:dateString];
[formatter release], formatter = nil;

and

ISO8601DateFormatter *formatter = [[ISO8601DateFormatter alloc] init];
NSString *dateString = [formatter stringFromDate:[twitch dateTwitched]];
[formatter release], formatter = nil;
Matthew