iOS 9 中的日期格式不起作用
Date formatting in iOS 9 not working
我在 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"]];
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")
我在 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"]];
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")