Converting a NSString into NSDate
I have date string: Monday, October 11, 2010. How can I create a NSDate object out of it and then get different components like day, month, date, year from it. 开发者_JAVA技巧Please note that format/locale of this string may change at runtime.
Use an NSDateFormatter to create the NSDate, then you can access its components through NSDate properties (you'll need to adjust the format string below):
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
if(NSDate *myDate = [df dateFromString:string]) {
//Do something with myDate
}
another possibility:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
...
精彩评论