NSDateFormatter dateFromString 和 iPhone 中的 24 小时格式混淆 [英] NSDateFormatter dateFromString and iPhone in 24 Hour Format Confusion

查看:25
本文介绍了NSDateFormatter dateFromString 和 iPhone 中的 24 小时格式混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题.我以 12 小时格式获取传入的时间字符串,并将它们转换为 NSDate 对象.当 iPhone 是 12 小时制时,没问题.但是当它采用 24 小时制时,事情就会出错.下面是一些示例代码来演示:

I'm having a problem. I get incoming time strings in 12-hour format, and I'm turning them into NSDate objects. When the iPhone is in 12 hour format, no problem. But when it's in 24 Hour format, things go wrong. Here's some sample code to demonstrate:

NSString *theTime = @"3:19 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"h:mm a"]; // "3:19 PM"
NSDate *date = [formatter dateFromString:theTime];
NSString *theString = [formatter stringFromDate:date];

在 24 小时模式下,日期是 1970-01-01 03:19:00,theString 是3:19" - 错误

In 24 hour mode, date is 1970-01-01 03:19:00, and theString is "3:19" - WRONG

在 12 小时模式下,日期是 1970-01-01 15:19:00,theString 是3:19 PM" - RIGHT

In 12 hour mode, date is 1970-01-01 15:19:00, and theString is "3:19 PM" - RIGHT

所以...问题 1:为什么设备的 24 小时设置会覆盖我的日期格式化程序设置?

So... question 1: why is the device's 24 hour setting overriding my date formatter setting?

更重要的是,问题 2:如何将 12 小时制正确转换为 24 小时制?

and more importantly, question 2: How do I get a proper conversion from 12 hour time to 24 hour time?

我已经有代码来检测手机是否处于 24 小时模式,但除了在字符串中四处挖掘并将 3 换成 15 之外,似乎没有一种干净的方法可以做到这一点.

I already have code to detect if the phone is in 24 hour mode, but other than digging around in the string and swapping the 3 with a 15, there doesn't seem to be a clean way to do this.

推荐答案

不确定您是否仍然需要它,但我遇到了类似的问题,通过设置日期格式化程序的语言环境已解决.也就是说,如果要强制其为 12 小时模式,无论用户的 24/12 小时模式设置如何,都应将 locale 设置为 en_US_POSIX.

Not sure if you still need it, but I've had a similar problem which got solved by setting the locale for the date formatter. That is, if you want to force it to 12-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale to en_US_POSIX.

这篇关于NSDateFormatter dateFromString 和 iPhone 中的 24 小时格式混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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