How to create a date object for tomorrow at 8am

坚强是说给别人听的谎言 提交于 2019-12-03 21:40:45
John Sauer

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 doesn't have [NSDate dateWithNaturalLanguageString:@"tomorrow at 8:00 am"]. Thanks, rmaddy, for pointing that out.

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
        }

    }

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!