我有一个应用程序,用户选择他们工作的星期几,所以星期一到星期日是选项。我需要能够获得他们将要工作的第一天的日期。因此,如果当天是星期六,他们选择工作的第一天是星期一,我需要能够获得该星期一的日期吗?
感激不尽。
答案 0 :(得分:3)
首先,您需要为工作日创建枚举:
extension Date {
enum Weekday: Int {
case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
}
}
其次创建一个扩展名以返回所需的下一个工作日:
extension Date {
var weekday: Int {
return Calendar.current.component(.weekday, from: self)
}
func following(_ weekday: Weekday) -> Date {
// **edit**
// Check if today weekday and the passed weekday parameter are the same
if self.weekday == weekday.rawValue {
// return the start of day for that date
return Calendar.current.startOfDay(for: self)
}
// **end of edit**
return Calendar.current.nextDate(after: self, matching: DateComponents(weekday: weekday.rawValue), matchingPolicy: .nextTime)!
}
}
现在您可以使用以下方法:
let now = Date()
now.following(.sunday) // "Mar 10, 2019 at 12:00 AM"
now.following(.monday) // "Mar 11, 2019 at 12:00 AM"
now.following(.tuesday) // "Mar 12, 2019 at 12:00 AM"
now.following(.wednesday) // "Mar 6, 2019 at 12:00 AM"
now.following(.thursday) // "Mar 7, 2019 at 12:00 AM"
now.following(.friday) // "Mar 8, 2019 at 12:00 AM"
now.following(.saturday) // "Mar 9, 2019 at 12:00 AM"