NSDateFormatter Trouble?

2019-07-11 04:16发布

I am trying to parse an RSS feed, but the date is hard to parse. The date string is: publishedDate = "2013-01-08T20:09:02.000Z"

Here is my code:

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

Why is date returning nil? Also, i am trying to convert UTC time to CST Time.

3条回答
姐就是有狂的资本
2楼-- · 2019-07-11 04:19

For stime that includes miliseconds use "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 output:
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 output:
original UTC 2013-02-08 20:09:02 +0000 now local: 2013-02-08

查看更多
趁早两清
3楼-- · 2019-07-11 04:29

Use

 [utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'000Z'"];
查看更多
Summer. ? 凉城
4楼-- · 2019-07-11 04:40

Just change your time zone name to CST and change the setDateFormat as follows:

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);
查看更多
登录 后发表回答