Reputation: 1323
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)?
Upvotes: 3
Views: 5316
Reputation: 589
This explains the reason behind this problem and how to solve it.
Upvotes: 5
Reputation: 479
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)
Upvotes: 1
Reputation: 41
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
Upvotes: 4