如何使用Swift查找下一个工作日或周末的日期
Swift Date扩展实现下一个工作日/周末的查找
实现逻辑
基于原有查找指定星期日期的扩展,我们可以先封装通用的星期匹配方法,再分别封装工作日、周末的便捷调用入口,兼容默认的周历规则,也支持自定义调整。
首先明确系统Calendar的weekday规则:
- 1 = 周日
- 2 = 周一
- 3 = 周二
- 4 = 周三
- 5 = 周四
- 6 = 周五
- 7 = 周六
完整代码实现
import Foundation extension Date { /// 通用方法:查找下一个属于指定星期集合的日期 /// - Parameters: /// - weekdays: 目标星期集合,1=周日,2=周一,...,7=周六 /// - includeToday: 若今天符合条件是否返回今天 /// - Returns: 匹配的日期,无匹配则返回nil func nextDate(matching weekdays: Set<Int>, includeToday: Bool = false) -> Date? { let calendar = Calendar.current var currentDate = includeToday ? self : calendar.date(byAdding: .day, value: 1, to: self)! while true { let currentWeekday = calendar.component(.weekday, from: currentDate) if weekdays.contains(currentWeekday) { return currentDate } guard let nextDate = calendar.date(byAdding: .day, value: 1, to: currentDate) else { return nil } currentDate = nextDate } } /// 查找下一个工作日(默认规则:周一到周五) func nextWorkday(includeToday: Bool = false) -> Date? { return nextDate(matching: [2,3,4,5,6], includeToday: includeToday) } /// 查找下一个周末日期(默认规则:周六、周日,返回最先到来的日期) func nextWeekendDay(includeToday: Bool = false) -> Date? { return nextDate(matching: [1,7], includeToday: includeToday) } /// 可选扩展:获取下一个完整周末的起始日期(即周六) func nextWeekendStartDate() -> Date? { return nextDate(matching: [7], includeToday: false) } }
使用示例
let currentDate = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd EEEE" dateFormatter.locale = Locale(identifier: "zh_CN") // 查找下一个工作日 if let nextWorkday = currentDate.nextWorkday() { print("下一个工作日:\(dateFormatter.string(from: nextWorkday))") } // 查找下一个周末日期 if let nextWeekend = currentDate.nextWeekendDay() { print("下一个周末:\(dateFormatter.string(from: nextWeekend))") } // 查找下一个周末的周六 if let weekendStart = currentDate.nextWeekendStartDate() { print("下一个周末起始日(周六):\(dateFormatter.string(from: weekendStart))") }
自定义调整说明
- 若需适配不同地区的工作日规则,直接修改
nextWorkday方法中传入的weekdays集合即可 - 若需指定时区,替换
Calendar.current为对应时区的Calendar实例即可 - 代码兼容iOS 10+、macOS 10.12+及以上所有系统版本
内容的提问来源于stack exchange,提问作者Jack Stark
相关产品推荐
相关产品推荐

