Swift - 从一系列工作日中获取下一个日期 [英] Swift - Get next date from a array of weekdays

查看:68
本文介绍了Swift - 从一系列工作日中获取下一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

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

I'm making an app where I have tasks with due dates and once they are done I want to set a new due date for according to a new date according to a day of the week repeat pattern chosen by the user.

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

Im saving due dates as Date. Im saving the repeat pattern as Int32 (1 for Sunday, 2 for Monday, 4 for Tuesday...) but I can easily get it to an array of Strings or numbers representing each day

问题

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

How do I get the next due date as Date (so I can repeat the task)?

示例

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

if I have a task that is completed on a Saturday and has repeat pattern of every Monday and Wednesday I want it to be set to the next Monday. If it is them completed on Monday or Tuesday I want to set the next Wednesday.

选择重复图案的照片

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

Month is never selected when other days are selected. I know how to deal with the Month. The problem is just with the days of the week

推荐答案

永远不要使用 86400 进行日期计算,CalendarIndexSet 有强大的功能方法:

Never use 86400 for date math, Calendar and IndexSethave powerful methods to do that:

// 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)

这篇关于Swift - 从一系列工作日中获取下一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆