Travis M.
Travis M.

Reputation: 11257

NSDateFormatter swapping between Style and Format

Is it safe to use the same NSDateFormatter and swap between Style and Format definitions? For example:

NSDateFormatter *df = [NSDateFormatter new];
df.dateStyle = NSDateFormatterMediumStyle;
df.timeStyle = NSDateFormatterMediumStyle;
NSLog(@"Medium Style / Medium Time: %@", [df stringFromDate:[NSDate date]]);
df.dateFormat = @"MMM/d/yy hh:mm:ss";
NSLog(@"Custom Format: %@", [df stringFromDate:[NSDate date]]);
df.dateStyle = NSDateFormatterFullStyle;
df.timeStyle = NSDateFormatterNoStyle;
NSLog(@"Full Style/ No Time: %@", [df stringFromDate:[NSDate date]]); 
// ^-- how does it know to stop using the format I set before?

In the very last line, how does the NSDateFormatter know to stop using the date format I specified before? Is this safe to do reliably?

Upvotes: 1

Views: 187

Answers (1)

rmaddy
rmaddy

Reputation: 318924

The date formatter uses the style if format is nil. So add the following line:

df.dateFormat = nil;

when you want to go back to use the style.

Upvotes: 3

Related Questions