iPhone 设置为 12 小时制时的 NSDateFormatter
我正在使用 NSDateFormatter 将 NSDate 格式化为“HH:mm 'on' dd MMMM YYYY”格式。
这是我编写的代码:
[dateFormatter setDateFormat:@"HH:mm 'on' dd MMMM YYYY"];
[dateFormatter setLocale:[NSLocale currentLocale]];
然后,我使用 stringFromDate 方法更新标签以显示“2010 年 9 月 22 日 12:45 的数据”。
NSString *timeAndDateUpdated = [[NSString alloc] initWithFormat:@"Data from %@.", [dateFormatter stringFromDate:date]]
如果 iPhone 上的时间设置为 24 小时制,则标签会正确更新,但如果设置为 12 小时制,则标签显示“数据来自(空)”。
有谁知道如何解决这个问题?
谢谢。
I'm using an NSDateFormatter to format an NSDate to be in the format "HH:mm 'on' dd MMMM YYYY".
This is the code I've written:
[dateFormatter setDateFormat:@"HH:mm 'on' dd MMMM YYYY"];
[dateFormatter setLocale:[NSLocale currentLocale]];
Then I'm updating a label to display "Data from 12:45 on 22 September 2010", using the method stringFromDate.
NSString *timeAndDateUpdated = [[NSString alloc] initWithFormat:@"Data from %@.", [dateFormatter stringFromDate:date]]
The label is updated correctly if the time on the iPhone is set to 24-hour, but if it's set to 12-hour, the label displays "Data from (null)".
Does anyone know how to solve this problem?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我也刚刚遇到了这个。
看起来日期是由 NSDateFormatter 根据区域设置进行解析的,即使您显式指定了日期格式字符串!
因此,在这种情况下,24 小时时钟 HH 将被忽略,并尝试使用设备上设置的 12 小时时钟进行解析。
修复它的方法是显式覆盖 NSDateFormatter 的区域设置;在此示例中,将其设置为 en_US_POSIX 将在解析小时时强制使用 24 小时时钟,即
I just ran into this too.
It appears that dates are parsed by the NSDateFormatter according to locale, even if you explicitly specify a date format string!
So in this case, the 24-hour clock HH is being ignored and it's trying to parse using the 12-hour clock as set on the device.
The way to fix it is to explicitly override the NSDateFormatter's locale; in this example setting it to en_US_POSIX will force the 24-hour clock to be used when parsing the hour, i.e.
如果日期仅呈现给用户(“on”表明它是),我不会强制使用日期格式。使用长/中/短日期和时间样式要友好得多,它们的行为取决于用户的区域格式:
另请注意,配置 NSDateFormatter 的成本非常昂贵(大约 10 毫秒 IIRC)。如果您只显示一次并且不经常更新,那很好,但如果每个表格单元格都有一个日期,则滚动会有点慢。我最近通过缓存日期格式化程序使图形绘制速度提高了 50 倍......
If the date is solely presented to the user (the "on" suggests it is), I wouldn't force a date format. It's much more friendly to use the long/medium/short date and time styles, which behave according to the user's region format:
Also note that configuring an NSDateFormatter is incredibly expensive (about 10 ms IIRC). It's fine if you're only going to display it once and not update very often, but it makes scrolling a bit slow if you have a date per table cell. I recently made graph-drawing 50x faster by cacheing date formatters...
我在 3.1.2 和 4.1 上运行了这段代码,设置了 12 小时和 24 小时,效果很好。
如果此代码不适合您,请检查 NSDateformatter 或 NSDate 的自定义扩展/类别。
I ran this code on 3.1.2 and 4.1 with both 12 and 24 hour settings and it worked fine.
If this code doesn't work for you, check for custom extensions/categories for NSDateformatter or NSDate.