Assemble date object from integers?
Given three integers, representing a day, month and year, what code would assemble those开发者_开发知识库 integers into a date object?
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]);
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).
精彩评论