将日期和时间合并到单个 NSDate 中时出现问题
我正在尝试使用此方法将一个 NSDate
的时间值(小时、分钟、秒)与第二个 NSDate
的日期值(日、月、年)结合起来:
+ (NSDate *)combineDate:(NSDate *)date withTime:(NSDate *)time {
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit |
NSWeekdayCalendarUnit) fromDate:date];
NSDateComponents *timeComponents = [gregorian components:(NSDayCalendarUnit |
NSWeekdayCalendarUnit) fromDate:time];
NSDateComponents *comp = [NSDateComponents alloc];
[comp setSecond:[timeComponents second]];
[comp setHour:[timeComponents hour]];
[comp setMinute:[timeComponents minute]];
[comp setYear:[dateComponents year]];
[comp setMonth:[dateComponents month]];
[comp setDay:[dateComponents day]];
NSDate *combDate = [gregorian dateFromComponents:comp];
[gregorian release];
[comp release];
return combDate;
}
...但是它返回的实际上是乱码(例如,年份显示为“1”)。有人看出这个方法有什么问题吗?
I am trying to combine the time value (hours, minutes, seconds) of one NSDate
with the date value (day, month, year) of a second NSDate
with this method:
+ (NSDate *)combineDate:(NSDate *)date withTime:(NSDate *)time {
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit |
NSWeekdayCalendarUnit) fromDate:date];
NSDateComponents *timeComponents = [gregorian components:(NSDayCalendarUnit |
NSWeekdayCalendarUnit) fromDate:time];
NSDateComponents *comp = [NSDateComponents alloc];
[comp setSecond:[timeComponents second]];
[comp setHour:[timeComponents hour]];
[comp setMinute:[timeComponents minute]];
[comp setYear:[dateComponents year]];
[comp setMonth:[dateComponents month]];
[comp setDay:[dateComponents day]];
NSDate *combDate = [gregorian dateFromComponents:comp];
[gregorian release];
[comp release];
return combDate;
}
... but what it's returning is effectively gibberish (the year comes out as "1", for example). Anybody see what's wrong with this method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是 Swift 2 中的
Here it is in Swift 2
(Swift + 扩展) 是你的朋友:
(Swift + extension) are your friend:
我使用了错误的日历组件。这是更正后的函数(现在适用于 ARC):
I was using the wrong calendar components. Here's the corrected function (now for ARC):
斯威夫特 3 扩展:
Swift 3 extension: