iPhone SDK NSString To NSDate

人盡茶涼 提交于 2019-11-30 03:04:07

问题


I got a string from parsing a XML file which looks like this: Fri, 09 Apr 2010 00:00:45 +0200 and the corresponding pattern should be this "EEE, dd MMM yyyy HH:mm:ss ZZ", but I get (null).

This is my code:

NSString *dateString = @"Fri, 09 Apr 2010 00:00:45 +0200";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZ"];

NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"date:%@",date); // result date:(null)

Edit:

This works for me now, I had to switch to en-US locale:

NSLocale* usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setLocale:usLocale];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZ"];

NSDate *date = [dateFormatter dateFromString:dateString];

回答1:


Your code worked for me when I changed this line:

[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZ"];

to this line:

[dateFormatter setDateFormat:@"EEE',' dd MMM yyyy HH:mm:ss ZZ"];


来源:https://stackoverflow.com/questions/2618807/iphone-sdk-nsstring-to-nsdate

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