2

我正在尝试解析 RSS 提要,但日期很难解析。日期字符串是:publishedDate = "2013-01-08T20:09:02.000Z"

这是我的代码:

NSDateFormatter *utc = [[NSDateFormatter alloc] init];
[utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *dtUTC = [utc dateFromString: publishedDate];

NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yyyy-MM-dd"];
[dfLocal setTimeZone:[NSTimeZone localTimeZone]];

NSString *time =[dfLocal stringFromDate:dtUTC];
NSLog(@"original UTC %@  now local: %@", dtUTC, time);

为什么date返回零?另外,我正在尝试将 UTC 时间转换为 CST 时间。

4

3 回答 3

2

采用

 [utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'000Z'"];
于 2013-01-09T02:57:22.620 回答
1

对于包括毫秒的时间,请使用“S”。

[utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'"];

NSString *publishedDate = @"2013-01-08T20:09:02.000Z";
NSDateFormatter *utc = [[NSDateFormatter alloc] init];
[utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'"];
NSDate *dtUTC = [utc dateFromString: publishedDate];
NSLog(@"dtUTC: %@", dtUTC);

NSLog 输出:
dtUTC:2013-01-08 20:09:02 +0000

SDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yyyy-MM-dd"];
[dfLocal setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSString *time =[dfLocal stringFromDate:dtUTC];
NSLog(@"original UTC %@  now local: %@", dtUTC, time);

NSLog 输出:
原始 UTC 2013-02-08 20:09:02 +0000 现在本地:2013-02-08

于 2013-01-09T03:03:26.137 回答
1

只需将您的时区名称更改为 CST 并将 setDateFormat 更改如下:

NSDateFormatter *cst = [[NSDateFormatter alloc] init];
    [cst setTimeZone:[NSTimeZone timeZoneWithName:@"CST"]];
    [cst setDateFormat:@"yyyy-mm-dd'T'HH:mm:ss.'000Z'"];
    NSDate *theCST = [cst dateFromString:publishedDate];
    NSLog(@"theCST is %@", theCST);
于 2013-01-09T03:09:08.793 回答