Make a new NSDate by combining two NSDates

前端 未结 5 1777
故里飘歌
故里飘歌 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

    It's not as compact as darvids0n's, but it works.

    NSDate* day1 = [datePicker dateValue];
    NSDate* day2 = [NSDate date];
    
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:day1;
    NSInteger day = [components day];    
    NSInteger month = [components month];
    NSInteger year = [components year];
    
    components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit fromDate:day2];
    NSInteger hour = [components hour];    
    NSInteger minute = [components minute];
    NSInteger second = [components second];
    
    NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
    [comps setDay:day];
    [comps setMonth:month];
    [comps setYear:year];
    [comps setHour:hour];
    [comps setMinute:minute];
    [comps setSecond:second];
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *day3 = [cal dateFromComponents:comps];
    

    or

    NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
    [tempFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* message = [NSString stringWithFormat:@"%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second];
    NSDate *day3 = [tempFormatter dateFromString:message];
    

提交回复
热议问题