converting string to NSDate issue: [__NSDate Length] unrecognized selected

徘徊边缘 提交于 2019-12-05 01:05:42

You get that error because you are passing a NSDate object to dateFromString:.

Add an NSLog and you will see that:

NSString *inputString = [self.measurements objectAtIndex:indexNumber.row];
if ([inputString isKindOfClass:[NSDate class]]) {
    NSLog(@"inputString is of type NSDate");
}

Also, here is how to reproduce your error:

NSString *inputString = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date = [dateFormatter dateFromString:inputString];

That means that the array self.measurements contains NSDate objects and not NSString objects.


When you correct your current problem, you will probably encounter a new one because you don't use the correct date format. To parse date strings of type: 2012-03-09 23:00:00 +0000 you should use the following date format:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zz"];

Either do as sch suggests, or if you don't need the time at all, you can just truncate the string you feed to your dateFormatter. E.g. like so:

NSDate *date = [dateFormatter dateFromString:[inputString substringToIndex:9]];

Where 9 is an index, up to which you want to take a chunk of string.

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