Building NSDate from integers (year … second) with Cocoa/objective-C

痞子三分冷 提交于 2020-01-02 01:40:07

问题


I have year, mont, ... , second in integer type, and I need to build NSDate from them. I tried this code, but I got (null).

NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];
NSString* message = [NSString stringWithFormat:@"%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second];
NSDate *day3 = [tempFormatter dateFromString:message];

What's wrong with this code?


回答1:


instead of

[tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];

write

[tempFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];



回答2:


It would be more straightforward to create an NSDateComponents with your date components, and then use NSCalendar's dateFromComponents: to convert it to a date. The documentation for NSDateComponents has an example of how to do exactly this:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:day];
[comps setMonth:month];
[comps setYear:year];
[comps setHour:hour];
[comps setMinute:minute];
[comps setSecond:second];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [cal dateFromComponents:comps];
[comps release];


来源:https://stackoverflow.com/questions/5306367/building-nsdate-from-integers-year-second-with-cocoa-objective-c

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