NSDateFormatter“HH”在iOS 8设备上返回上午/下午 [英] NSDateFormatter "HH" returning am/pm on iOS 8 device

查看:350
本文介绍了NSDateFormatter“HH”在iOS 8设备上返回上午/下午的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在很难过。我很高兴使用NSDateFormatter没有任何问题,但今天我注意到我的一个应用程序在iOS 6.3的iPhone 6 plus设备上给了我疯狂的结果 - 虽然它似乎在其他设备/模拟器上很好。调查它有这样的代码:

I am stumped right now. I have been happily using NSDateFormatter with no problems, but today I noticed that one of my apps is giving me crazy results on an iPhone 6 plus device with iOS 8.1.3 - while it seems to be fine on other devices/simulator. Looking into it there is this code:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
[dateFormatter setDateFormat:@"HH"];
NSInteger hour= [[dateFormatter stringFromDate:datetime] integerValue];

这会导致(在设备上)0到12小时的表示法,因为超出原因我,如果我在那时打印[dateFormatter stringFromDate:datetime]我得到下午4点!

This results (on the device) to 0-12 hour notation, because for a reason that is beyond me, if I print [dateFormatter stringFromDate:datetime] at that point I get "4 pm"!

我缺少什么?

推荐答案

编辑:
要查看问题,请在手机设置中选择默认为24小时制的地区,例如英国或法国。然后,从设置中禁用24小时时间。现在,如果您在不设置其语言环境的情况下创建NSDateFormatter,则HH将不起作用。
要解决此问题,请设置区域设置(即使是当时手机所在的区域设置),例如对于上面的代码,我们可以添加:

Edited: To see the problem, in your phone settings select a region that defaults to a 24-hour time, for example "United Kingdom" or "France". Then, disable the "24 hour time" from the settings. Now if you create an NSDateFormatter without setting its locale, "HH" will not work. To circumvent this problem, set the locale (even to the same one the phone is at that moment) e.g. for the above code we could add:

dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

任何语言环境都可以使用,甚至是en_GB。这显然是一个错误,而不是unicode标准的某种奇怪表示,因为如果你设置了一个默认为12小时时间的区域,24小时时间滑块不会影响HH的工作方式,而如果您所在的区域默认为24小时,然后设置中的滑块将影响代码的工作方式。

Any locale will work, even en_GB. This is obviously a bug, and not some sort of strange representation of the unicode standard, because if you have set a region that defaults to 12 hour time, the "24 hour time" slider does not affect how "HH" works, while if you are on a region that defaults to 24 hour time, then that slider in the settings will affect how your code works.

这篇关于NSDateFormatter“HH”在iOS 8设备上返回上午/下午的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆