NSDate from NSString - dateFromString returns nil

2019-03-06 11:55发布

I want to get a NSDate object from a string of date, but it returns nil. What am I doing wrong? Thanks!

NSString *dateString = @"2012-04-05T13:27:32.369Z";

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate* date = [df dateFromString:dateString];
NSLog(@"1%@",date);
[df release];

3条回答
仙女界的扛把子
2楼-- · 2019-03-06 12:29

It should be yyyy for years

[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-06 12:40

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.

查看更多
迷人小祖宗
4楼-- · 2019-03-06 12:51

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

查看更多
登录 后发表回答