我正在尝试通过这种方法将一个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”表示)。有人看到这种方法有什么问题吗?
最佳答案
我使用了错误的日历组件。这是更正后的功能(现在适用于ARC):
+ (NSDate *)combineDate:(NSDate *)date withTime:(NSDate *)time {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:
NSGregorianCalendar];
unsigned unitFlagsDate = NSYearCalendarUnit | NSMonthCalendarUnit
| NSDayCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:unitFlagsDate
fromDate:date];
unsigned unitFlagsTime = NSHourCalendarUnit | NSMinuteCalendarUnit
| NSSecondCalendarUnit;
NSDateComponents *timeComponents = [gregorian components:unitFlagsTime
fromDate:time];
[dateComponents setSecond:[timeComponents second]];
[dateComponents setHour:[timeComponents hour]];
[dateComponents setMinute:[timeComponents minute]];
NSDate *combDate = [gregorian dateFromComponents:dateComponents];
return combDate;
}