xcode NSDateFormatter 在设备和模拟器上给出不同的值?什么是变通?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1803169/
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-09-14 18:58:34  来源:igfitidea点击:

NSDateFormatter gives different values on device and simulator? What is work around?

iphonecocoa-touchxcodensdateformatter

提问by Madhup Singh Yadav

I am using NSDateFormatter, the problem is with its consistency. If I use the kCFDateFormatterMediumStyle it gives the format as "Nov 26, 2009" in simulator but on device it gives "26-Nov-2009".

我正在使用 NSDateFormatter,问题在于它的一致性。如果我使用 kCFDateFormatterMediumStyle,它会在模拟器中提供“2009 年 11 月 26 日”的格式,但在设备上它会提供“26-Nov-2009”。

Now I have the question, Is this NSFormatter trustable means in near future or updates from apple can it change the style again?

现在我有一个问题,这个 NSFormatter 在不久的将来是否值得信赖,或者来自苹果的更新是否可以再次改变风格?

采纳答案by Daniel Tull

NSDateFormatter formats the date to the user's preference, based on the International settings on the device. As such you can never expect this string to be consistent because of the amount of different ways that dates are displayed across the world.

NSDateFormatter 根据设备上的国际设置将日期格式化为用户的偏好。因此,您永远不能期望这个字符串是一致的,因为日期在世界范围内的显示方式多种多样。

I've found the best way to format a date as a string (to use to give to webservers etc) is to use NSDateComponents and convert these to strings.

我发现将日期格式化为字符串(用于提供给网络服务器等)的最佳方法是使用 NSDateComponents 并将它们转换为字符串。

回答by Douglas Mayle

While the other answer mentioned above is technically correct, it doesn't give you the solution you are looking for. While the NSDateFormatter defaults to using user locales (and is, as such, not going to give you useful results) you can request a specific locale to get consistent results:

虽然上面提到的另一个答案在技术上是正确的,但它并没有为您提供您正在寻找的解决方案。虽然 NSDateFormatter 默认使用用户语言环境(因此,不会为您提供有用的结果),但您可以请求特定语言环境以获得一致的结果:

NSDateFormatter *frm = [[NSDateFormatter alloc] init];
[frm setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];

NSLocale *en_US = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[frm setLocale:en_US];
[en_US release];