Search code examples
iosswiftnsdate

how to get NSDate of a specific next day and time


I have some events for which I need to calculate NSDates. For example I'm trying to get the next Monday at 8:00 AM. So I tried some stuff but nothing works:

1.

let nextMonday = NSCalendar.currentCalendar().dateBySettingUnit(NSCalendarUnit.Weekday, value: 2, ofDate: startDate, options: NSCalendarOptions.MatchNextTime)
let nextMondayEight = NSCalendar.currentCalendar().dateBySettingUnit(NSCalendarUnit.Hour, value: 8, ofDate: nextMonday!, options: NSCalendarOptions.MatchNextTime)

I get:

2016-04-12 05:00:00 +0000

That's Tuesday at 8:00 (the time difference is my local time GMT -3).

2.

let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let comp = NSCalendar.currentCalendar().components(unitFlags, fromDate: NSDate())
comp.timeZone = NSTimeZone.localTimeZone()
comp.weekday = 1
comp.hour = 8
comp.minute = 0
comp.second = 0
let compDate = NSCalendar.currentCalendar().dateFromComponents(comp)

print("time: \(compDate!)")

I get:

2016-04-11 05:00:00 +0000

That's today at 8:00 and not next Monday at 8:00.


Any suggestions? Thanks


Solution

  • NSCalendar has a method nextDateAfterDate:matchingComponents:options for this kind of date math.

    let calendar = NSCalendar.currentCalendar()
    let components = NSDateComponents()
    components.hour = 8 // 8:00
    components.weekday = 2 // Monday in Gregorian Calendar
    
    let nextMondayEightOClock = calendar.nextDateAfterDate(NSDate(), matchingComponents: components, options: .MatchStrictly)