Reputation: 32247
I tried a substringFromIndex:-4
but got an error. How do I cut & keep just the end of a string? Or rather, substr
from the end?
eg.
12/12/2012 -> 2012
Upvotes: 3
Views: 5463
Reputation: 41005
You have to calculate it yourself I'm afraid. This will work:
NSString *theWholeString = @"12/12/2012";
NSString *substring = [theWholeString substringFromIndex:[theWholeString length] - 4];
In the above case you could also do it with a split, like this:
NSString *theWholeString = @"12/12/2012";
NSArray *components = [theWholeString componentsSeparatedByString:@"/"];
NSString *substring = [components objectAtIndex:2]; // the third item in the array
That's probably easier if you want to extract each part of the date, one after another.
For completeness's sake, if you're parsing dates, the best way to do it is using NSDateFormatter, like this:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//first get the date object
[formatter setDateFormat:@"dd/MM/yyyy"]; // make sure you get dd and MM the right way round if you're American
NSDate *date = [formatter dateFromString:@"12/12/2012"];
//now output the part you wanted
[formatter setDateFormat:@"yyyy"];
NSString *justTheYear = [formatter stringFromDate:date];
It's overkill if you just want the year, but if you start trying to chop up more complex date/time strings, it's much more flexible.
Upvotes: 9
Reputation: 10733
Try:
NSString *dateString = @"12/12/2012";
NSLog(@"%@", [dateString substringFromIndex:[dateString length]-4]);
Upvotes: 8