objective-c - 从日、月、年生成 NSDate

标签 objective-c ios cocoa-touch cocoa nsdate

我正在尝试从月日和年生成 NSDate(全部为整数格式)。

现在我的尝试是这样的:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSNumber *day = [dataSource valueForKey:@"day"];
NSNumber *month = [dataSource valueForKey:@"month"];
NSNumber *year = [dataSource valueForKey:@"year"];
[components setDay:[day intValue]];
[components setMonth:[month intValue]];
[components setMonth:[year intValue]];
NSDate *_date = [calendar dateFromComponents:components];

但是,当日 = 24、月 = 8、年 = 2011 时,_date 会输出以下内容:

0168-07-25 04:56:02 +0000

我一定做错了什么,但我不知道是什么。有人知道会发生什么吗?

最佳答案

您的代码中有错字:(最后一行应该是 setYear:)

 [components setDay:[day intValue]];
 [components setMonth:[month intValue]];
 [components setYear:[year intValue]];

关于objective-c - 从日、月、年生成 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7664786/

相关文章:

ios - CATransform3DMakeRotation 框架

objective-c - 贝塞尔路径看是否交叉

ios - 在iOS swift/Objective C中实现Diffie Hellman生成公钥和私钥的方法有哪些?(除了Chilkat)

ios - 如何获取scrollView.keyboardDismissMode委托(delegate)?

ios无法显示数据库中的图像

iphone - 强制加载/卸载 View

iphone - ipAd 不适合 iPad 横向模式

objective-c - 将选定的音乐文件整合到视频中

ios - 检查 IOS 中两个位置的接近度

objective-c - Xcode 4.4 无法重命名类/变量