Conversion of NSString to NSDate failing

前提是你 提交于 2019-12-25 07:23:44

问题


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


来源:https://stackoverflow.com/questions/12989509/conversion-of-nsstring-to-nsdate-failing

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