2013-01-09 36 views
2

我想解析一个RSS源,但日期很难解析。日期字符串是:publishedDate = "2013-01-08T20:09:02.000Z"NSDateFormatter麻烦?

这里是我的代码:

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时间。

+0

什么是'publishedDate'? – wigging

+0

串... 2013-01-08T20:09:02.000Z –

回答

2

使用

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

它的工作原理,但我的日期都具有相同的月份?这是01 –

+0

米需要在大写。 – msk

+0

它仍然给我相同的01 –

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年1月8日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年2月8日20时09分02秒现在+0000地方:2013年2月8日

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);