我有一些事件需要计算 NSDate
。
例如,我试图在下周一上午 8:00 到达。
所以我尝试了一些东西但没有任何效果:
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)
关于ios - 如何获取特定的第二天和时间的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36544325/