问题
Given three integers, representing a day, month and year, what code would assemble those integers into a date object?
回答1:
You should look at NSDateComponents
:
int y = 2011;
int m = 1;
int d = 15;
NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setYear:y];
[dc setMonth:m];
[dc setDay:d];
NSLog(@"%@: %@", [[dc date] class], [dc date]);
回答2:
NSDateFormatter uses the Unicode Standard for parsing date strings into dates. So, format your integers into a date string and then use and NSDateFormatter to parse it:
// assume year, month and day are integers that are formatted properly and don't
// include invalid ranges
NSString* dateString = [NSString stringWithFormat:@"%04d %02d %02d", year, month, day];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
// Choose a format of YEAR MONTH DATE per the standard
[formatter setDateFormat:@"yyyy MM dd"];
NSDate* date = [formatter dateFromString:dateString];
[formatter release];
You can set the format string to whatever format floats your boat, as long as you use the Unicode Standard (linked above) and you convert your integers into the same format (obviously).
来源:https://stackoverflow.com/questions/4743903/assemble-date-object-from-integers