Domanda

I have a string that is a date, like this @"dd/mm/yyyy" and I want to split this string in 3 small strings with day, month and year. I've succeeded on doing it with the day using this code:

self.dayLabel.text = [string substringToIndex:2];

but how do I get the middle values, like the month?

È stato utile?

Soluzione

Try this:

NSString *string = @"dd/mm/yyyy";
NSArray *components = [string componentsSeparatedByString:@"/"];

NSString *day = components[0];
NSString *month = components[1];
NSString *year = components[2];

Altri suggerimenti

There are many ways to parse strings with NSString / ObjC

However if your input data is always going to be the same this is probably the quickest way to grab the month:

NSString *monthString = [timestampString substringWithRange:NSMakeRange(3,2)];

You should look at NSScanner.

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top