Is there a better way to find midnight tomorrow?

前端 未结 6 2200
天涯浪人
天涯浪人 2021-02-13 22:05

Is there a better way to do this?

-(NSDate *)getMidnightTommorow {
    NSCalendarDate *now = [NSCalendarDate date];
    NSCalendarDate *tomorrow = [now dateByAdd         


        
6条回答
  •  孤街浪徒
    2021-02-13 22:44

    From the documentation:

    Use of NSCalendarDate strongly discouraged. It is not deprecated yet, however it may be in the next major OS release after Mac OS X v10.5. For calendrical calculations, you should use suitable combinations of NSCalendar, NSDate, and NSDateComponents, as described in Calendars in Dates and Times Programming Topics for Cocoa.

    Following that advice:

    NSDate *today = [NSDate date];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = 1;
    NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];
    [components release];
    
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    components = [gregorian components:unitFlags fromDate:tomorrow];
    components.hour = 0;
    components.minute = 0;
    
    NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];
    
    [gregorian release];
    [components release];
    

    (I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.)

    Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although dateFromComponents: may tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.

提交回复
热议问题