tags:

views:

34

answers:

1

Why does this message not return a string:

NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *formattedDate = (@"Date for today %@:", [dateFormatter stringFromDate:today]);
+2  A: 

That expression does return an NSString, but without formatting. To format an NSString properly, you use the +stringWithFormat: method:

NSString* formattedDate = [NSString stringWithFormat:@"Date for today %@:",
                           [dateFormatter stringFromDate:today]];

The expression a, b is a "comma expression". It will evaluate a and b in sequence, and return the value of b. In you case, it will return the string of date only.

Most of the case, you do not want to use a comma expression.


Also, the dateFormatter needs to be configured before using. For instance,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
...
... [dateFormatter stringFromDate:today] ...
...
[dateFormatter release];
KennyTM
I have just tried that, it returns "Date for today:" without the actual date though?
TheLearner
@The: You need to call `-setTimeStyle:` and `-setDateStyle:` for the dateFormatter before using it.
KennyTM