1

i have a NSString variables like this dd-MM-YYYY exemple 30-05-2011 . How can i get day in a variable , month in variable and year in variable ? thank you

user567
  • 3,712
  • 9
  • 47
  • 80

3 Answers3

3

Use NSDateFormatter and NSDateComponents.

In particular, for the format "dd-MM-YYYY":

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"dd'-'MM'-'yyyy"];
// Your date represented as a NSDate
NSDate *date = [formatter dateFromString:myDateString];
// Now, use NSCalendar / NSDateComponents to get the components
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                                          fromDate:date];

Now you're free to access [comps day], [comps month], and [comps year].

See here for a description of all the format-parsing options. Keep in mind that NSDateFormatter also supports older versions of this standard, so you'll have to be careful.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • thank you but i have an EXC bad access when i trie it.daparatureFly.date is a string , it's not a problem ? . this is the code NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; [formatter setDateFormat:@"dd'-'MM'-'yyyy"]; NSDate *date = [formatter dateFromString:daparatureFly.date]; NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date]; NSLog(@"year : %@",[comps year]); – user567 May 24 '11 at 03:35
  • You can't use `%@` when displaying a number. `[comps year]` will be a `NSInteger`, so you should use `%d` or `%ld`. – jtbandes May 24 '11 at 03:43
2

You could do something along the lines of ...

    NSString *dateAsString = @"30-05-2011";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"d-MM-yyyy"];
    NSDate *datePlain = [formatter dateFromString:dateAsString]; 
    [formatter release];

and then use the NSDate object datePlain

Sai
  • 3,819
  • 1
  • 25
  • 28
  • thank you but then how i will take them separetly with datePlain ? – user567 May 24 '11 at 03:46
  • @Mehdi Maybe I should have explicitly specified that you could use NSCalendar in conjunction with the NSDate object. I see that @jtbandes has answered the question. – Sai May 24 '11 at 05:08
1

Take a look at the dateFromString: method of NSDateFormatter.

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *d = [df dateFromString:@"2011-05-10"];
[df release];

You can do whatever you need to do with the NSDate object.

csano
  • 13,266
  • 2
  • 28
  • 45