将rss pubdate字符串转换为NSDate对象时遇到了一些问题。
<pubDate>Fri, 09 Sep 2011 15:26:08 +0200</pubDate>
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:currentDate];
NSLog(@"DateObject : '%@'", date);
[dateFormatter release];
我总是得到
[44157:10d03] DateObject : '(null)'
答案 0 :(得分:7)
你需要:
dd
代替d
,因为这一天是零填充ZZ
代替Z
,因为它不包含时区缩写名称更多信息:http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns
当我运行时:
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *str = @"Fri, 09 Sep 2011 15:26:08 +0200";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZ"];
NSDate *date = [dateFormatter dateFromString:str];
NSLog(@"DateObject : %@", date);
[dateFormatter release];
[pool drain];
return 0;
}
我明白了:
EmptyFoundation [19926:407] DateObject:2011-09-09 13:26:08 +0000
答案 1 :(得分:1)
首先,您可以尝试以下代码:
NSString *str = @"Mon, 19 Oct 2015 14:27:28 +0800";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZ"];
NSDate *date = [dateFormatter dateFromString:str];
NSLog(@"DateObject : %@", date);
但是,如果您的DateObject
仍然是null
,则您的语言区域位置不正确"en_US_POSIX"
。您需要更改您的区域设置。
NSString *str = @"Mon, 19 Oct 2015 14:27:28 +0800";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZ"];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
NSDate *date = [dateFormatter dateFromString:str];
NSLog(@"DateObject : %@", date);
结果是:
DateObject:2015-10-19 06:27:28 +0000
答案 2 :(得分:0)
使用:
NSArray *array=[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
通过空格和换行符分割pubDate,然后使用数组的索引获取要显示的每个元素。
答案 3 :(得分:0)
我使用此代码格式化Wordpress RSS提要日期:
+ (NSDate *)parseWordpressDate:(NSString *)dataWp {
NSArray *array=[dataWp componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//Tue, 04 Mar 2014 11:00:36 +0000
//day = index 1, month = 2, year = 3
NSString *yyear = [array objectAtIndex:3];
NSString *mmonth = [array objectAtIndex:2];
NSString *dday = [array objectAtIndex:1];
NSDateFormatter *dateFormatterGMTAware = [[NSDateFormatter alloc] init];
[dateFormatterGMTAware setDateFormat:@"yyyy-MMM-dd"];
NSString *dateString = [NSString stringWithFormat:@"%@-%@-%@",yyear,mmonth,dday];
NSDate *data = [dateFormatterGMTAware dateFromString:dateString];
return data;
}