Take the 2-minute tour ×

I have a string like this: @"10/04/2011" and I want to save only the "10" in another string. How can I do that?

share|improve this question
add comment

6 Answers

up vote 219 down vote accepted
NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* day = [foo objectAtIndex: 0];
share|improve this answer
Using [foo firstObject] might be better in general case because it will properly handle empty array too. –  Bobrovsky Feb 18 at 8:52
@Bobrovsky in the general case, it would be better to validate the string to make sure it is a date. This is just an example that answers the specific question. It's also more generalisable to get any of the three date parts. –  JeremyP Jun 26 at 8:57
add comment

Either of these 2:

NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];

Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.

The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.

share|improve this answer
add comment

Use [myString componentsSeparatedByString:@"/"]

share|improve this answer
add comment

I have formatted the nice solution provided by JeremyP above into a more generic reusable function below:

///Return an ARRAY containing the exploded chunk of strings
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
    return [stringToBeExploded componentsSeparatedByString: delimiter];
share|improve this answer
Why not just use componentsSeparatedByString directly? –  John Gibb Mar 25 '13 at 15:58
because I'm using it across several projects, so if anything changes, I just have to change the body of the wrapper function instead of at several places. But if you are just using it once, so yes it makes more sense using it directly Cheers! –  7php Mar 28 '13 at 7:29
componentsSeparatedByString hasn't changed in something like two decades. Do you wrap all Apple method calls in case they change? You must type a lot. –  tooluser May 23 at 20:26
add comment

Its working fine

NSString *dateString = @"10/10/2010";//Date 
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];
share|improve this answer
add comment

NSString *day = [@"10/04/2011" componentsSeparatedByString:@"/"][0];

share|improve this answer
add comment

Your Answer


