How to create a date object for tomorrow at 8 am

I am usually good at this, but I am having problems with the object NSDate

. I need an object NSDate

for tomorrow at 8am (relatively). How can I do this and what is the simplest method?

+2


source to share


3 answers


Here's how WWDC 2011 Session 117 - Performing Calendar Calculations taught me:

NSDate* now = [NSDate date] ;

NSDateComponents* tomorrowComponents = [NSDateComponents new] ;
tomorrowComponents.day = 1 ;
NSCalendar* calendar = [NSCalendar currentCalendar] ;
NSDate* tomorrow = [calendar dateByAddingComponents:tomorrowComponents toDate:now options:0] ;

NSDateComponents* tomorrowAt8AMComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:tomorrow] ;
tomorrowAt8AMComponents.hour = 8 ;
NSDate* tomorrowAt8AM = [calendar dateFromComponents:tomorrowAt8AMComponents] ;

      



Too bad iOS has no [NSDate dateWithNaturalLanguageString:@"tomorrow at 8:00 am"]

. Thanks rmaddy for pointing this out.

+14


source


In Swift 2.1 :



    let now = NSDate()
    let tomorrowComponents = NSDateComponents()
    tomorrowComponents.day = 1

    let calendar = NSCalendar.currentCalendar()
    if let tomorrow = calendar.dateByAddingComponents(tomorrowComponents, toDate: now, options: NSCalendarOptions.MatchFirst) {

        let flags: NSCalendarUnit = [.Era, .Year, .Month, .Day]
        let tomorrowValidTime: NSDateComponents = calendar.components(flags, fromDate: tomorrow)
        tomorrowValidTime.hour = 7

        if let tomorrowMorning = calendar.dateFromComponents(tomorrowValidTime) {
            return tomorrowMorning
        }

    }

      

+1


source


Swift 3 +

private func tomorrowMorning() -> Date? {
    let now = Date()
    var tomorrowComponents = DateComponents()
    tomorrowComponents.day = 1
    let calendar = Calendar.current
    if let tomorrow = calendar.date(byAdding: tomorrowComponents, to: now) {
        let components: Set<Calendar.Component> = [.era, .year, .month, .day]
        var tomorrowValidTime = calendar.dateComponents(components, from: tomorrow)
        tomorrowValidTime.hour = 7
        if let tomorrowMorning = calendar.date(from: tomorrowValidTime)  {
            return tomorrowMorning
        }

    }
    return nil
}

      

0


source







All Articles