Given the year, month and day, everything is in int, how will I generate NSDate

I think the solution is really simple, I just have not seen it on the Internet.

Suppose I get int year, int month, int day, int hour, int min, int sec .. how do I generate an NSDate?

I know that we can use [NSDate initWithString:], but I think it gets complicated if month / day / hour / min / sec are single digits.

+7
cocoa nsdate
source share
2 answers

Suppose I get int year, int month, int day, int hour, int min, int sec .. how do I generate an NSDate?

Put the ints in the NSDateComponents object, then ask the NSCalendar Object to change it to a date .

+13
source share

This one here pretty much sums up how to do this.

//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]; 

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

just realized that you said you were given ints ... you could do it in this line format:

 [NSString stringWithFormat:@"%i/%i/%i", month, day, year]; 
0
source share

All Articles