Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make NSDateFormatter display locale-specific date?

Tags:

uikit

iphone

I am using NSDateFormatter to set my date in my iPhone app, and dates are showing up properly. However, I am finding all the locales (my app supports up to 12 different languages) are sticking to the date format I specify via setDateFormat. Ideally, I want the date format to appear in a form natural to the region setting for the user, instead of following my format (which works well for English but may not be natural for other locales).

Following is my code:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"MMMM dd, yyyy kk:mm:ss"];

    self.creationDate.text = [dateFormatter stringFromDate:creationTimeStamp];
like image 923
Boon Avatar asked Aug 28 '09 18:08

Boon


1 Answers

I would try the following NSDateFormatter API instead:

+ (NSString *)localizedStringFromDate:(NSDate *)date
              dateStyle:(NSDateFormatterStyle)dateStyle
              timeStyle:(NSDateFormatterStyle)timeStyle;

Like so:

self.creationDate.text = [NSDateFormatter localizedStringFromDate:creationTimeStamp
                                          dateStyle:NSDateFormatterMediumStyle
                                          timeStyle:NSDateFormatterShortStyle];

That should give you the output you're looking for, tidy up the code a little, and keep you from having to manage some spurious memory.

like image 91
fbrereto Avatar answered Nov 09 '22 22:11

fbrereto