Why not convert your NSString
containing your date into an NSDate
instance then use the NSDateComponents
class to get the year/month/day like below.
NSString *dateString = @"01/01/2012"; // Our initial date as a string
// Set the instance of the Date Formatter up and set the format of the date we want
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
// Set an instance of the date class up and convert the string value of our dateString to an actual date
NSDate *dateVal = [[NSDate alloc] init];
dateVal = [dateformatter dateFromString:dateString];
// Set the instance of the Date Components class up and specify the components we want and from what date value
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:dateVal];
// Get the year/month/day as ints
int year = [components year];
int month = [components month];
int day = [components day];
// Then using the stringWithFormat: method we can set the int values to the correct label as a string
self.dayLabel.text = [NSString stringWithFormat:@"%d", day];
self.monthLabel.text = [NSString stringWithFormat:@"%d", month];
self.yearLabel.text = [NSString stringWitjFormat:@"%d", year];
This way would probably work out best for you in every case for the different date formats that you could be given such as DD/MM/YYYY
or MM/DD/YYYY
or YYYY/MM/DD
etc so if just parsing the string you could end up with random values so it would be best to convert it to an NSDate
instance always have the same date format as it will convert all the different formats to one so you know the value you are getting is the one you want.