Conversion of NSString to NSDate failing

2019-08-27 12:55发布

问题:

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?

回答1:

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


回答2:

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"];