NSDateFormatter麻烦?
我试图parsing一个RSS提要,但date很难parsing。 datestring是: 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时间。
使用
[utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'000Z'"];
只需将您的时区名称更改为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);
包含毫秒的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