无论12h-24h设置,使用NSDateFormatter的字符串日期 [英] Date from String using NSDateFormatter regardless 12h-24h setting

查看:218
本文介绍了无论12h-24h设置,使用NSDateFormatter的字符串日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我的问题是关于日期格式和字符串。
我的应用程序从互联网下载一些表示日期的字符串。日期格式是这样的:2010-05-24 at 20:45
我需要将此字符串转换为NSDate对象以执行一些日期操作。
我试过这段代码:

  NSString * dateString = @2010-05-24 at 20:45/ /实际上从互联网上下载
NSDateFormatter * myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@yyyy-MM-dd'at'HH:mm];
NSDate * dateFromString = [myDateFormatter dateFromString:dateString];

只要iPhone设置为24小时制,这似乎工作得很好。只要我在常规设置中切换到12h时钟,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)?

解决方案

This explains the reason behind this problem and how to solve it.

这篇关于无论12h-24h设置,使用NSDateFormatter的字符串日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆