converting string to NSDate issue: [__NSDate Lengt

2019-04-20 16:39发布

indexNumber.row is a date like 2012-03-09 23:00:00 +0000. I've tried a handful of different ways to get my date into an NSDate, but I keep getting the title error.

NSString *inputString = [self.measurements objectAtIndex:indexNumber.row];

// Convert string to date object
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:inputString ];
NSLog(@"date format is: %@", date);

Any ideas why I get the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDate length]: unrecognized selector sent to instance 0x6ca0c60'

2条回答
你好瞎i
2楼-- · 2019-04-20 16:59

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.

查看更多
萌系小妹纸
3楼-- · 2019-04-20 17:26

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"];
查看更多
登录 后发表回答