NSDateFormatter 无法返回设置为 12 小时制的英国地区的日期时间 [英] NSDateFormatter fails to return a datetime for UK region with 12 hour clock set

查看:112
本文介绍了NSDateFormatter 无法返回设置为 12 小时制的英国地区的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码适用于我可以确定的每个区域/区域设置组合,除非我将手机设置为 12 小时制的英国区域.谁能告诉我为什么?

这适用于包括英国在内的所有地区,设置为 12 小时制:

NSDateFormatter *theDateFormatter = [[NSDateFormatter alloc] init];theDateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";NSString *theLastFetchDateString = @"2015-11-13T01:47:52.4630000Z";NSDate *theLastFetchDate = [theDateFormatter dateFromString:theLastFetchDateString];

这适用于除英国以外的所有地区,采用 12 小时制:

NSDateFormatter *theDateFormatter = [[NSDateFormatter alloc] init];theDateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";NSString *theLastFetchDateString = @"2015-11-13T18:14:44.1230000Z";NSDate *theLastFetchDate = [theDateFormatter dateFromString:theLastFetchDateString];

在第二种情况下,LastFetchDate 始终为零.

我看到的主要区别是第二个日期以 24 小时格式存储,其中解析设备以 12 小时格式存储,但格式化程序 HH 应该能够处理,是吗?

另一件奇怪的事情,它可能只是一个显示问题,是英国 12 小时制时间格式为a.m."或下午"美国 12 小时制将它们格式化为AM"或PM".

解决方案

您正在解析 RFC 3339/ISO 8601 日期.因此,您应该将格式化程序的 locale 设置为 en_US_POSIX.

theDateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

请参阅 Apple 技术问答 1480.>

This code works for every region/locale combination I can determine EXCEPT if I set my phone to UK region with the 12 hour clock set. Can anyone tell me why?

This works for every region including the UK with 12 hour clock set:

NSDateFormatter *theDateFormatter = [[NSDateFormatter alloc] init];
theDateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";

NSString *theLastFetchDateString = @"2015-11-13T01:47:52.4630000Z";
NSDate *theLastFetchDate = [theDateFormatter dateFromString:theLastFetchDateString];

This works in every region EXCEPT the UK with the 12 hour clock set:

NSDateFormatter *theDateFormatter = [[NSDateFormatter alloc] init];
theDateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";

NSString *theLastFetchDateString = @"2015-11-13T18:14:44.1230000Z";
NSDate *theLastFetchDate = [theDateFormatter dateFromString:theLastFetchDateString];

In the second case, theLastFetchDate is always nil.

The main difference I see is the second date is stored in 24 hour format where the parsing device is in 12 hour format, but the formatter HH should be able to handle that, yeah?

The other weird thing, and it is probably just a display thing, is the UK 12 hour clock formats times with 'a.m.' or 'p.m.' where the US 12 hour clock formats them as 'AM' or 'PM'.

解决方案

You are parsing a RFC 3339/ISO 8601 date. As such, you should set the locale of the formatter to be en_US_POSIX.

theDateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

See Apple Technical Q&A 1480.

这篇关于NSDateFormatter 无法返回设置为 12 小时制的英国地区的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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