在iPhone上使用NSDateFormatter,保护语言环境但丢失日期组件

Joh*_*ger 12 iphone nsdateformatter

这是一个有点棘手的问题.我在iPhone上使用NSDateFormatter,但我想只显示没有年份组件的标准日期.但保留其日期的用户区域设置格式.

我可以使用轻松覆盖格式

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

但现在日期是我的en-nz格式,例如7月7日星期三下午12:01.所以我完全杀死了世界上任何其他用户的语言环境.

我想说.

为我提供此用户区域的正确本地化日期,但省略年份组件.

由于日期显示为字符串,我很想将日期归结为日期,然后通过将其从字符串中删除来删除年份组件.

Ami*_*aor 16

从iOS 4.0开始,正确的方法(参见WWDC 2012中的本地化会话),支持开箱即用的不同语言环境变体,正在使用上面提到的以下API

+dateFormatFromTemplate:options:locale:
Run Code Online (Sandbox Code Playgroud)

例如,要获得没有年份的长日期格式:

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
Run Code Online (Sandbox Code Playgroud)


Joe*_*e V 11

你可以尝试类似的东西:

//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];
Run Code Online (Sandbox Code Playgroud)

一种黑客,但它应该工作.

编辑:您可能需要删除的字符串的出现@"y,"@" y"第一,如果你结束了一些时髦的额外的空格或逗号.


小智 10

上面的答案的问题是,@"y,"并且@" y"都依赖于本地化.我刚刚在计算机上将日期和时间格式设置为日语,韩语和其他一些格式.您会发现有时候年份用当地语言的符号表示,或者有时使用句号,或者其他一些可能性.因此,如果您希望保持正确的本地化依赖性,那么您还需要搜索并替换所有这些可能性.

有一种类方法+dateFormatFromTemplate:options:locale:可能有所帮助,虽然它没有采用日期或时间风格,因此它不那么灵活.

我不确定苹果的其他API是否有一个很好的解决方案.但即便如此,也不清楚他们将自己的本地化分离成组件.没有这个,这基本上是一项不可能完成的任务.