Date from String using NSDateFormatter regardless 12h-24h setting

北慕城南 提交于 2019-12-22 09:39:56

问题


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)?


回答1:


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




回答2:


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];

use "hh" instead of "HH" in setting date format




回答3:


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.

let stringDate = "2017-03-15T11:37:16-03:00" // ISO8601 formatted string

let iso8601Formatter = DateFormatter()
iso8601Formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
iso8601Formatter.locale = Locale(identifier: "en_US_POSIX")
iso8601Formatter.date(from: stringDate)


来源:https://stackoverflow.com/questions/2764225/date-from-string-using-nsdateformatter-regardless-12h-24h-setting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!