objective-c - iOS 9 中的日期格式不起作用

标签 objective-c nsdateformatter ios9

<分区>

我在 iOS 9 中遇到日期格式问题,它在 iOS 8 上工作正常,当我在 iOS 9 的模拟器中测试它时它也工作,但是当在 iOS 9 的真实设备上测试它时我变得空了。下面是我正在使用的代码

NSLog(@"String Date: '%@'", stringDate);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormat dateFromString:stringDate];
NSLog(@"Date: %@", date);

在日志中我得到:

String Date: '8/29/2015 4:13:39 PM'
Date: (null)

此外,如果我使用大写字母 h(H 或 HH),我得到的小时总是 10。

最佳答案

尝试在日期格式化程序上设置语言环境。

[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

来自 Apple Documentation :

If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences.

编辑: Swift 版本

dateFormat.locale = NSLocale(localeIdentifier: "en_US_POSIX")

关于objective-c - iOS 9 中的日期格式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32932484/

相关文章:

objective-c - NSWindow 设置框架高于屏幕

ios - NSDateFormatter 中的本地化

swift - 如何从 iOS 9 更新已弃用的 statusBarStyle

objective-c - 将秒格式化为 hh :ii:ss

objective-c - copyWithZone 被调用

objective-c - iOS 图像处理(失真)

objective-c - 如何在iOS中获取本地格式化的日期模式字符串?

ios - 为什么日期格式化程序崩溃?

iOS 9 多行标签在集合可重用标题 View 中自动布局不起作用

iOS联系人如何通过电话号码获取联系人