Conversion of NSString to NSDate failing

2019-08-27 13:03发布

I have the following piece of code..

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/YYYY HH:mm"];
NSString *dateString = @"10/27/2012 18:00";
NSDate *parsedDate = [dateFormatter dateFromString:dateString] ;
NSLog(@"Parsed Date.. %@",[parsedDate description]);

I am getting the NSLog statement as Parsed Date.. 2011-12-25 00:00:00 +0000. I would appreciate any help in resolving this. I just want to convert that NSString to its NSDate equivalent. Tried using NSTimeZone as well, but no effect. What am I missing here?

2条回答
Deceive 欺骗
2楼-- · 2019-08-27 13:37

You need to use lower case year indication, yyyy instead of YYYY:

[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];

If you want to get the timezone right you need to set the timezone of the NSDateFormatter. By default it uses the timezone of your device. For the time at GMT use the following.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
NSString *dateString = @"10/27/2012 18:00";
NSDate *parsedDate = [dateFormatter dateFromString:dateString] ;
NSLog(@"Parsed Date.. %@",[parsedDate description]);
查看更多
小情绪 Triste *
3楼-- · 2019-08-27 13:45

You are using an incorrect format string. See the documentation. Basically, capital YYYY is "week of year year". Try to use lowercase yyyy instead, i.e.

[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
查看更多
登录 后发表回答