NSString to NSDate using NSDateFormatter returns null

混江龙づ霸主 提交于 2019-12-13 05:30:33

问题


dateFromString returns me null when I am trying to convert NSString to NSDate here is my code:

    NSString *dateString = @"Wed 16 Oct 2013";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale systemLocale]];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:@"EEE dd MMM yyyy"];
    [dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
    NSDate *myDate = [dateFormatter dateFromString: dateString];

Please, give me any suggestions about this.


回答1:


It's a locale issue and it's sort of the same of NSDateFormatter Strings in iOS 7, just the other way around.

Probably in your system locale Wed or/and Oct are not valid valid literals for a weekday or/and a month.

Try setting the locale to en_US or to currentLocale

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

or

NSLocale *locale = [NSLocale currentLocale];



回答2:


For more formatting style http://cybersam.com/ios-dev/quick-guide-to-ios-dateformatting

NSString *dateString = @"Wed 16 Oct 2013";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"EEE dd MMM yyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"%@", dateFromString);


来源:https://stackoverflow.com/questions/19544675/nsstring-to-nsdate-using-nsdateformatter-returns-null

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