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

拥有回忆 提交于 2019-12-05 00:25:55
Joe V

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.

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

The problem with the answer above is that @"y," and @" y" are both localization dependent. I just played around with setting the date and time format on my computer to Japanese, Korean and a number of other formats. You'll find that sometimes the year is represented by a symbol in the local language, or sometimes a period is used, or a number of other possibilities. So you'd need to search and replace all those possibilities as well, if you hope to maintain correct localization dependence.

There is a class method +dateFormatFromTemplate:options:locale: which may help, although it doesn't take date or time style and so it's not as flexible.

I'm not sure that there is a good solution with additional APIs from Apple. But even then it's not clear that they have their own localizations separated out into components. Without out that, this is essentially an impossible task.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!