Reputation: 35
I am reading in a file of strings. Each string looks something like:
!AIVDO,1,1,,B,11b4N?HPs0KLrBDIStg;q?w22<06,0*5A,21/10/2011 12:01:13 PM
What I have done so far is:
NSArray *arrayFromString = [theString componentsSeparatedByString:@","];
NSString *dateString = [tempArrayFromAISString objectAtIndex:7];
// dateString = @"21/10/2011 12:01:13 PM";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"d/M/yyyy h:mm:ss a"];
NSDate *date = [dateFormat dateFromString:dateString];
This returns an NSDate of (null).
The string is set ok because when I output it with NSLog it looks good.
The date formatter is ok because if I uncomment the line commented out and set the date string myself it works.
Any ideas as to why the string from the array does not work?
Thanks in advance for any help.
Upvotes: 0
Views: 135
Reputation: 35
There was a newline character at the end because I was reading from a file. I fixed it with:
dateString = [dateString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
This gets rid of the end of line character.
Upvotes: 0
Reputation: 2134
Your example contains a typo. arrayFromString
≠ tempArrayFromAISString
This works for me
NSString *theString = @"!AIVDO,1,1,,B,11b4N?HPs0KLrBDIStg;q?w22<06,0*5A,21/10/2011 12:01:13 PM";
NSArray *arrayFromString = [theString componentsSeparatedByString:@","];
NSString *dateString = [arrayFromString objectAtIndex:7];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"d/M/yyyy h:mm:ss a"];
NSDate *date = [dateFormat dateFromString:dateString];
NSLog(@"%@", date);
Upvotes: 0