Assemble date object from integers?

孤者浪人 提交于 2019-12-11 06:18:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!