ios NSDateFormatter 没有显示完整的月份名称,只有一位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12115545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:52:07  来源:igfitidea点击:

NSDateFormatter not showing full month name, only single digit number

iosnsdatensdateformatter

提问by Chris

Not sure what the issue is, but instead of getting a month name "July", I get "07".

不确定问题是什么,但我得到的不是月份名称“七月”,而是“07”。

dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocale systemLocale]];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];    
[dateFormat setDateFormat:@"MMMM dd, h:mm a"];

I have tried M, MM, MMM, MMMM, and all of them give me a number, instead of the month name, though with different amounts of leading 0s.

我试过 M、MM、MMM、MMMM,它们都给了我一个数字,而不是月份名称,尽管前导 0 的数量不同。

回答by Chris

Turns out to be an issue with the second line, setLocale. I assume that the system won't default to using english month names when the localehas been manually set? I live in an english speaking locale, but maybe it doesn't matter.

原来是第二行的问题,setLocale. 我认为系统不会默认使用英语月份名称时,locale已手动设置?我住在说英语的地方locale,但也许这无关紧要。

In any case, not setting the locale fixes the month name issue.

在任何情况下,不设置语言环境都可以解决月份名称问题。

dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];    
[dateFormat setDateFormat:@"MMMM dd, h:mm a"];

回答by J2theC

The problem is the locale, not the format. Check this out:

问题是语言环境,而不是格式。看一下这个:

http://waracle.net/mobile/iphone-nsdateformatter-date-formatting-table/

http://waracle.net/mobile/iphone-nsdateformatter-date-formatting-table/

Basically, "MMMM" will give you the full name for the month.

基本上,“MMMM”会给你月份的全名。

回答by Fabian Kreiser

-systemLocaleis not what you want here. It returns a fallback locale if no other locale fits. Use -currentLocaleto get the user's current locale.

-systemLocale不是你想要的。如果没有其他语言环境适合,它会返回一个后备语言环境。使用-currentLocale来获取用户当前的语言环境。

Also:
You should use NSDateFormatter's +dateFormatFromTemplate:options:locale:method to get the correct date format. In some languages the day comes before the month, etc. and vice versa.

另外:
您应该使用NSDateFormatter's+dateFormatFromTemplate:options:locale:方法来获取正确的日期格式。在某些语言中,日期在月份之前,等等,反之亦然。