Annotation Extras and NSDateFormatter


#1

I spent about an hour trying to figure out why this code wouldn’t give me a string with the current date and time:

NSDate *now = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; NSString *nowString = [[NSString alloc]initWithString:[dateFormatter stringFromDate:now]];

Turns out NSDateFormatter requires some formatting before returning the expected string. When I add these two lines after creating dateFormatter everything works fine:

[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
What’s odd is that this requirement isn’t documented anywhere, as far as I can tell.

Am I missing something?

mb


#2

I was stuck on the exact same issue until I read your post, so thank you for clearing that up.
Also, there was one part that you missed in the documentation that does state this. In “NSDateFormatter Class Reference” Overview, there is a line that reads: “…you should accept the default settings established on initialization and specify the format using setDateStyle:, setTimeStyle:, and appropriate style constants (see NSDateFormatterStyle—these are styles that the user can configure in the International preferences panel in System Preferences).”


#3

Thanks. I read that sentence but interpreted differently than what they obviously intended. The sentence before the line you quoted talks about the many attributes that are part of the class that can be modified. But they go on to say you shouldn’t modify them. Instead, use setDateStyle and setTimeStyle. When they say “you should accept the default settings established on initialization” it sounds like those defaults are set for you during initialization.

Maybe it’s just me but it’s not as clear as it could be.