问题
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. Please note that format/locale of this string may change at runtime.
回答1:
another possibility:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
...
回答2:
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
}
来源:https://stackoverflow.com/questions/3910920/converting-a-nsstring-into-nsdate