2

我在将 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)'
4

4 回答 4

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] 日期对象:2011-09-09 13:26:08 +0000

于 2011-09-10T16:43:52.947 回答
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);

结果是:

日期对象:2015-10-19 06:27:28 +0000

于 2015-10-19T07:29:35.827 回答
0

利用 :

  NSArray *array=[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

通过空格和换行符拆分 pubDate,然后使用数组的索引获取要显示的每个元素。

于 2014-04-07T09:26:16.703 回答
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;

  }
于 2014-04-15T09:05:48.790 回答