NSDate from NSString - dateFromString returns nil

时光总嘲笑我的痴心妄想 提交于 2019-12-02 07:47:15

The "Z" must be quoted:

NSDateFormatter* df = [[NSDateFormatter alloc]init];
NSString *dateString = @"2012-04-05T13:27:32.369Z";
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate* date = [df dateFromString:dateString];
NSLog(@"1: %@",date);

NSString *newDateString = [df stringFromDate:date];
NSLog(@"2: %@",newDateString);

NSLog output:

1: 2012-04-05 17:27:32 +0000
2: 2012-04-05T13:27:32.369

Keep in mind that NSLog uses the NSDate default formatter with the current timezone.

See: Date_Field_Symbol_Table

It should be yyyy for years

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

Use NSDateFormatter to get a NSDate then use - (NSTimeInterval)timeIntervalSince1970 to get the seconds since 1970.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *date = [formatter dateFromString:@"2012-04-05T13:27:32.369Z"];
NSLog(@"Date: %@", date);
NSLog(@"1970: %f", [date timeIntervalSince1970]);
NSLog(@"sDate: %@", [formatter stringFromDate:date]);
[formatter release];

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!