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

查看:215
本文介绍了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,且字符串为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, 是3:19 PM - 右

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

:为什么设备的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小时模式设置如何,您都应该将区域设置为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天全站免登陆