Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 964
prosseek Avatar asked Mar 15 '11 00:03

prosseek


2 Answers

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];
like image 199
Anomie Avatar answered Sep 20 '22 13:09

Anomie


instead of

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

write

[tempFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
like image 40
AndersK Avatar answered Sep 22 '22 13:09

AndersK