0

我正在解析 RSS 提要并使用 NSDateFormatter,代码如下:

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"pubDate"]) {

        NSLog(@"CURRENT STRING %@", currentString);
        NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
        [df1 setDateFormat:@"EEE, d MMM yyyy hh:mm:ss ZZZZ"];
        NSDate *newDate = [df1 dateFromString:currentString];
        NSLog(@"NEW DATE %@", newDate);     

        }
}

以下是 CURRENT STRING 的日志,即提供给 dateformatter 的输入:

在此处输入图像描述

下图显示了输出 NEW DATE 的日志,其中包含一些空值:

在此处输入图像描述

我在 StackOverflow 上尝试了很多问题,说要使用 NSLocale 和其他东西,但它们对我不起作用。谁能指出问题?

4

2 回答 2

2

在解析特定的本地化日期时,您应该为这些日期提供正确的本地化。

还要注意 24( HH) 或 12( hh) 小时符号:

    NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
    df1.locale = locale = [[NSLocale alloc] initWithLocaleIdentifier:@"EN"];
    [df1 setDateFormat:@"EEE, d MMM yyyy HH:mm:ss ZZZZ"];
    NSDate *newDate = [df1 dateFromString:currentString];
    NSLog(@"NEW DATE %@", newDate);     
于 2013-09-18T11:59:19.923 回答
1

在 RSS 中,您在 NSLog 中看到的不一定是字符串的样子。

发生这种情况是因为最后有空格,最后有 \n。

所以你需要删除那些空格和新行,如下所示。

NSString *yourString = [NSString stringWithFormat:@"%@", [[feeds objectAtIndex:indexPath.row] objectForKey:@"myStringCode"]];
yourString = [yourString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

完成此操作后,尝试格式化日期。

于 2013-09-18T12:00:56.037 回答