Swift - 从一系列工作日中获取下一个日期

toi*_*lle 1 nsdate nscalendar swift swift3

语境

我正在制作一个应用程序,其中我有截止日期的任务,一旦完成,我想根据用户选择的星期几重复模式根据新日期设置新的截止日期。

我将截止日期保存为日期。我将重复模式保存为 Int32(星期日为 1,星期一为 2,星期二为 4...),但我可以轻松地将其保存为代表每一天的字符串或数字数组

问题

如何将下一个截止日期作为日期(以便我可以重复任务)?

例子

如果我有一个在星期六完成的任务并且每个星期一和星期三都有重复模式,我希望它被设置为下一个星期一。如果他们在周一或周二完成,我想设置下一个周三。

选择重复图案的照片

选择其他日期时,从不选择月份。我知道如何处理这个月。问题仅在于一周中的几天

vad*_*ian 5

永远不要86400用于日期数学,CalendarIndexSet有强大的方法来做到这一点:

// Put your weekday indexes in an `IndexSet`
let weekdaySet = IndexSet([1, 2, 4, 7]) // Sun, Mon, Wed and Sat

// Get the current calendar and the weekday from today
let calendar = Calendar.current
var weekday =  calendar.component(.weekday, from: Date())

// Calculate the next index
if let nextWeekday = weekdaySet.integerGreaterThan(weekday) {
    weekday = nextWeekday
} else {
    weekday = weekdaySet.first!
}

// Get the next day matching this weekday
let components = DateComponents(weekday: weekday)
calendar.nextDate(after: Date(), matching: components, matchingPolicy: .nextTime)
Run Code Online (Sandbox Code Playgroud)