Objective C - get the following day from today (tomorrow)

后端 未结 3 1538
青春惊慌失措
青春惊慌失措 2020-11-29 06:51

How can I check to see if a date is inherently TOMORROW?

I don\'t want to add hours or anything to a date like today, because if today is already 22:59,

相关标签:
3条回答
  • 2020-11-29 07:06

    You might be able to leverage NSCalendar/Calendar to create tomorrow:

    extension Calendar {
        var tomorrow: Date? {
            return date(byAdding: .day, value: 1, to: startOfDay(for: Date()))
        }
    }
    
    0 讨论(0)
  • 2020-11-29 07:23

    In iOS 8 there is a convenience method on NSCalendar called isDateInTomorrow.

    Objective-C

    NSDate *date;
    BOOL isTomorrow = [[NSCalendar currentCalendar] isDateInTomorrow:date];
    

    Swift 3

    let date: Date
    let isTomorrow = Calendar.current.isDateInTomorrow(date)
    

    Swift 2

    let date: NSDate
    let isTomorrow = NSCalendar.currentCalendar().isDateInTomorrow(date)
    
    0 讨论(0)
  • 2020-11-29 07:30

    Using NSDateComponents you can extract day/month/year components from the date representing today, ignoring the hour/minutes/seconds components, add one day, and rebuild a date corresponding to tomorrow.

    So imagine you want to add exactly one day to the current date (including keeping hours/minutes/seconds information the same as the "now" date), you could add a timeInterval of 24*60*60 seconds to "now" using dateWithTimeIntervalSinceNow, but it is better (and DST-proof etc) to do it this way using NSDateComponents:

    NSDateComponents* deltaComps = [[[NSDateComponents alloc] init] autorelease];
    [deltaComps setDay:1];
    NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];
    

    But if you want to generate the date corresponding to tomorrow at midnight, you could instead just retrieve the month/day/year components of the date representing now, without hours/min/secs part, and add 1 day, then rebuild a date:

    // Decompose the date corresponding to "now" into Year+Month+Day components
    NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
    // Add one day
    comps.day = comps.day + 1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
    // Recompose a new date, without any time information (so this will be at midnight)
    NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
    

    P.S.: You can read really useful advice and stuff about date concepts in the Date and Time Programming Guide, especially here about date components.

    0 讨论(0)
提交回复
热议问题