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?
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];
instead of
[tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];
write
[tempFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With