9

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?

prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

34

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];
Anomie
  • 92,546
  • 13
  • 126
  • 145
  • This is a much better way of doing it! The other way is effectively converting integer date "components" to a string, and from there to an NSDate! That's surely asking for trouble. – siburb Jan 03 '14 at 02:32
  • You can't use `NSGregorianCalendar`... it's deprecated, unfortunately. Completely remove the `NSCalendar *cal`'s initialization/release, and change `cal` in the creation of `date` to `[NSCalendar currentCalendar]`. **You can no longer specify the Gregorian calendar.** Also, you can simplify the creation of `comps` by changing the line to this: `[NSDateComponents new];` – DDPWNAGE Jun 17 '15 at 06:21
  • @DDPWNAGE: According to [this other post](https://stackoverflow.com/questions/25626823/how-to-support-nscalendar-with-both-ios-7-and-8), it was basically just renamed to `NSCalendarIdentifierGregorian`. Using `[NSCalendar currentCalendar]` won't work right if the current calendar is one of the other supported calendars. – Anomie Jun 17 '15 at 11:23
5

instead of

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

write

[tempFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
AndersK
  • 35,813
  • 6
  • 60
  • 86