使用 NSDateFormatter 从字符串中获取日期,无论 12 小时到 24 小时设置如何
今天我的问题是关于日期格式和字符串。 我的应用程序从互联网下载一些表示日期的字符串。日期格式始终是这样的:“2010-05-24 at 20:45” 我需要将此字符串转换为 NSDate 对象才能执行一些日期操作。 我尝试了这段代码:
NSString * dateString = @"2010-05-24 at 20:45" // actually downloaded from the internet
NSDateFormatter * myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
NSDate * dateFromString = [myDateFormatter dateFromString:dateString];
只要 iPhone 设置为 24 小时时钟,这似乎就可以完美工作。只要我在常规设置中切换到 12 小时时钟,就不会创建 NSDate 对象(并且应用程序会愉快地崩溃) 我读过其他人也有类似的问题,但我似乎没有找到解决方案。 现在的问题是: 只要我指定它应该使用哪种格式来解析字符串(它是不可修改的,因为它来自网络),NSDateFormatter 对用户设置是敏感的,这对我来说没有意义,有什么用检查用户设置? 更重要的是,如何执行我的任务(从字符串中获取 NSDate 对象,无论用户设置如何)?
Today my question is about date formats and strings.
My application downloads some strings representing dates from the internet. The date format is always like this: "2010-05-24 at 20:45"
I need to convert this string into an NSDate object in order to perform some date manipulations.
I tried this code:
NSString * dateString = @"2010-05-24 at 20:45" // actually downloaded from the internet
NSDateFormatter * myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
NSDate * dateFromString = [myDateFormatter dateFromString:dateString];
This seems to work perfectly fine as long as the iPhone is set to 24h clock. As long as I switch to 12h clock in the general settings the NSDate object is not created (and the application happily crashes)
I have read others having similar problems but I don't seem to find a solution.
Now the questions:
It doesn't make sense to me that the NSDateFormatter is sensible to user settings as long as I am specifying which format it is supposed to use to parse the string (which is not modifiable because it comes from the web), what's the use of checking user settings?
More important, how can I get my task performed (to get an NSDate object from the string regardless the user settings)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这解释了此问题背后的原因以及如何解决它。
This explains the reason behind this problem and how to solve it.
设置日期格式时使用“hh”而不是“HH”
use "hh" instead of "HH" in setting date format
我发现苹果的这篇文章准确地解释了这个问题! (https://developer.apple.com/library/content/qa /qa1480/_index.html)
但无论如何,简短的答案是您需要将区域设置设置为“en_US_POSIX”,以便它可以与任何用户设置的日期相关配置一起使用。
I've found this article from Apple that explains exactly this issue! (https://developer.apple.com/library/content/qa/qa1480/_index.html)
but anyway, the shortchanged answer is that you need to set the locale to "en_US_POSIX" for it to work with any user-set date related configs.