iOS 9中的日期格式不起作用 [英] Date formatting in iOS 9 not working
问题描述
我在iOS 9中的日期格式有问题,它在iOS 8上可以正常使用,并且当我在iOS 9的模拟器中对其进行测试时也可以使用,但是在使用iOS 9的真实设备上对其进行测试时,我可以越来越空了.以下是我正在使用的代码
I'm have a problem with date formatting in iOS 9, it works ok with iOS 8 and also it works when I'm testing it in simulator with iOS 9, but when a test it on real device with iOS 9 I'm getting null. Below is code that I'm using
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小时.
Also if I use uppercase h (H or HH) I'm always getting that hour is 10.
推荐答案
尝试在日期格式化程序上设置区域设置.
Try setting locale on your date formatter.
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
来自 Apple文档:
如果您使用固定格式的日期,则应首先设置 日期格式化程序的语言环境应为适合您的固定格式的语言环境 格式.在大多数情况下,最好的语言环境是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中的日期格式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!