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

回眸只為那壹抹淺笑 提交于 2019-12-05 19:47:43

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

pardhu
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

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