简体   繁体   English

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

[英]how to get NSDate of a specific next day and time

I have some events for which I need to calculate NSDate s.我有一些需要计算NSDate的事件。 For example I'm trying to get the next Monday at 8:00 AM.例如,我试图在下周一上午 8:00 到达。 So I tried some stuff but nothing works:所以我尝试了一些东西,但没有任何效果:

1. 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 2016-04-12 05:00:00 +0000

That's Tuesday at 8:00 (the time difference is my local time GMT -3).那是星期二的 8:00(时差是我当地时间 GMT -3)。

2. 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 2016-04-11 05:00:00 +0000

That's today at 8:00 and not next Monday at 8:00.那是今天的 8:00 而不是下周一的 8:00。


Any suggestions?有什么建议吗? Thanks谢谢

NSCalendar has a method nextDateAfterDate:matchingComponents:options for this kind of date math. 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM