Make a new NSDate by combining two NSDates

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

    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:day1];
    NSDate *day3 = [[NSCalendar currentCalendar] dateFromComponents:comps];
    
    unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:day2];
    day3 = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:day3 options:0];
    

    Sources:

    1. NSDateComponents Class Reference
    2. NSCalendar Class Reference

提交回复
热议问题