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
Asked
Active
Viewed 118 times
1
-
Dup of http://stackoverflow.com/questions/4380381/how-to-convert-string-to-date-in-objective-c – titaniumdecoy May 24 '11 at 03:16
-
@Jason @cs thank you but i can't just do it with Regular expression or sbstring ? – user567 May 24 '11 at 03:21
3 Answers
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
-
-
@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