Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSDateFormatter on the iPhone, protect locale but lose date components

This is a slightly tricky question. I am using NSDateFormatter on the iPhone but I wanted to only show a standard date without the years component. But retain the users locale formatting for their date.

I could easily override the formatting using

[dateFormatter setDateFormat:@"h:mma EEEE MMMM d"];  // hurl.ws/43p9 (date formatting)

But now the date is in my in en-nz format eg 12:01PM Wednesday July 7. So I have totally killed the locale for any other users around the world.

I would like to say.

Give me the correct localized date for this users region but omit the years component.

Since the date is being displayed as string, I am tempted to just fromat the date and then remove the year component by just cutting this out of the string.

like image 974
John Ballinger Avatar asked Jul 09 '09 02:07

John Ballinger


2 Answers

From iOS 4.0 the correct way of doing it (see the localization session from WWDC 2012), supporting different locale variations out of the box, is using the following API as mentioned above

+dateFormatFromTemplate:options:locale:

For example, to get a long date format without the year:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];  
NSString *longFormatWithoutYear = [NSDateFormatter dateFormatFromTemplate:@"MMMM d" options:0 locale:[NSLocale currentLocale]]; 
[dateFormatter setDateFormat:longFormatWithoutYear];
//format your date... 
//output will change according to locale. E.g. "July 9" in US or "9 de julho" in Portuguese
like image 156
Amir Naor Avatar answered Nov 15 '22 18:11

Amir Naor


You could try something like:

//create a date formatter with standard locale, then:

// have to set a date style before dateFormat will give you a string back
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

// read out the format string
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:@"y" withString:@""];
[dateFormatter setDateFormat:format];

Kind of a hack, but it should work.

Edit: You may want to remove occurrences of the strings @"y," and @" y" first, in case you end up with some funky extra spaces or commas.

like image 43
Joe V Avatar answered Nov 15 '22 19:11

Joe V