如何获取特定的第二天和时间的 NSDate

how to get NSDate of a specific next day and time

我有一些事件需要计算 NSDates。 例如,我想在下周一的 8:00 AM 开始。 所以我尝试了一些东西但没有任何效果:

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)

我得到:

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

那是星期二 8:00(时差是我当地时间 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!)")

我得到:

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

那是今天 8:00 而不是下周一 8:00。


有什么建议吗? 谢谢

NSCalendar 有一个方法 nextDateAfterDate:matchingComponents:options 用于这种日期数学运算。

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)