I have NSDate* day1
and NSDate* day2
. How can I make a NSDate* day3
by copying only year/month/day from day1 and hour/minute/second from d
For the records, here is a more general approach
@implementation NSDate (Additions)
- (void)assignFlags:(NSUInteger)unitFlags to:(NSDateComponents *)components {
NSDateComponents *myComponents =
[[NSCalendar currentCalendar] components: unitFlags
fromDate: self];
if (unitFlags & NSYearCalendarUnit)
[components setYear: [myComponents year]];
if (unitFlags & NSMonthCalendarUnit)
[components setMonth: [myComponents month]];
if (unitFlags & NSDayCalendarUnit)
[components setDay: [myComponents day]];
if (unitFlags & NSHourCalendarUnit)
[components setHour: [myComponents hour]];
if (unitFlags & NSMinuteCalendarUnit)
[components setMinute: [myComponents minute]];
if (unitFlags & NSSecondCalendarUnit)
[components setSecond: [myComponents second]];
}
- (NSDate *)dateByTakingComponents:(NSUInteger)unitFlags fromDate:(NSDate *)date {
NSUInteger allFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *allComponents = [[NSDateComponents alloc] init];
[date assignFlags: unitFlags to: allComponents];
[self assignFlags: allFlags & ~unitFlags to: allComponents];
NSDate *result = [[NSCalendar currentCalendar] dateFromComponents: allComponents];
[allComponents release];
return result;
}
@end
You can call it like this
NSDate *day3 =
[day2 dateByTakingComponents: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate: day1];