tags:

views:

148

answers:

3

I think the solution is really simple, I just haven't come across it online.

Suppose I am given int year, int month, int day, int hour, int min, int sec.. how do I generate NSDate out of it?

I know we can use [NSDate initWithString:] but I think it gets complicated if month/day/hour/min/sec are one digit numbers.

+1  A: 

This here pretty much sums up how to do it.

//create a string that looks like this, "October 22, 2009" or whatever the values are
NSString* d = [NSString stringWithFormat:@"%@ %@, %@", month, day, year];
NSDate* date = [NSDate dateWithNaturalLanguageString:d];

that link also shows other options for creating the date if you don't like this particular method.

just realized that you said you were given ints... you could do that with this string format:

[NSString stringWithFormat:@"%i/%i/%i", month, day, year];
Joel
This will return wrong results in many locales (any where the order of day, month, and year does not match how you created the string).
Peter Hosey
+5  A: 

Suppose I am given int year, int month, int day, int hour, int min, int sec.. how do I generate NSDate out of it?

Put the ints into an NSDateComponents object, then ask an NSCalendar object to change that into a date.

Peter Hosey
+1 this is the proper way to do it
Dave DeLong
A: 

Thanks a lot, Peter and Joel.

I tried the NSDateComponent solution and it worked just fine.

BU
Then you should accept his answer as correct. :)
Dave DeLong