我在 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")