Parse jtring date with objective-c
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
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.
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
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.
精彩评论