开发者

Given year, month and day, all in int, how would I generate an NSDate

开发者 https://www.devze.com 2022-12-22 20:56 出处:网络
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 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 o开发者_运维技巧ne digit numbers.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号