views:

90

answers:

2

I'm using an NSDateFormatter to format an NSDate to be in the format "HH:mm 'on' dd MMMM YYYY".

This is the code I've written:

[dateFormatter setDateFormat:@"HH:mm 'on' dd MMMM YYYY"];
[dateFormatter setLocale:[NSLocale currentLocale]];

Then I'm updating a label to display "Data from 12:45 on 22 September 2010", using the method stringFromDate.

NSString *timeAndDateUpdated = [[NSString alloc] initWithFormat:@"Data from %@.", [dateFormatter stringFromDate:date]]

The label is updated correctly if the time on the iPhone is set to 24-hour, but if it's set to 12-hour, the label displays "Data from (null)".

Does anyone know how to solve this problem?

Thanks.

A: 

I ran this code on 3.1.2 and 4.1 with both 12 and 24 hour settings and it worked fine.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm 'on' dd MMMM YYYY"];
    [dateFormatter setLocale:[NSLocale currentLocale]];

    NSString *timeAndDateUpdated = [NSString stringWithFormat:@"Data from %@.", [dateFormatter stringFromDate:[NSDate date]]];

    NSLog(@"%@", timeAndDateUpdated);

If this code doesn't work for you, check for custom extensions/categories for NSDateformatter or NSDate.

TyB
+1  A: 

If the date is solely presented to the user (the "on" suggests it is), I wouldn't force a date format. It's much more friendly to use the long/medium/short date and time styles, which behave according to the user's region format:

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

[timeFormatter setDateStyle:NSDateFormatterNoStyle];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];

NSString * timeAndDate = [NSString stringWithFormat:"%@ on %@",
  [timeFormatter stringFromDate:date],
  [dateFormatter stringFromDate:date]];

Also note that configuring an NSDateFormatter is incredibly expensive (about 10 ms IIRC). It's fine if you're only going to display it once and not update very often, but it makes scrolling a bit slow if you have a date per table cell. I recently made graph-drawing 50x faster by cacheing date formatters...

tc.
Thanks. I thought it would be OK to force the data format because the app will only be available in the UK. Is it still best to use your method?Also, the date is displayed once on the screen and isn't changed very often.
Tom W
The user can still configure the date format (e.g. 12- vs 24-hour); it's generally a good idea to respect the user's wishes.
tc.