NSDateFormatter麻烦?

时间:2013-01-09 02:51:40

标签: ios xcode nsdate nsdateformatter utc

我正在尝试解析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返回nil?此外,我正在尝试将UTC时间转换为CST时间。

3 个答案:

答案 0 :(得分:2)

使用

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

答案 1 :(得分:1)

对于包含毫秒的stime,请使用“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

答案 2 :(得分: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);