Make a new NSDate by combining two NSDates

前端 未结 5 1750
故里飘歌
故里飘歌 2021-02-15 11:11

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

5条回答
  •  执笔经年
    2021-02-15 11:46

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

提交回复
热议问题