只是寻找一个简单的解决方案,以编程方式确定母亲节(五月的第二个星期日)或父亲节(六月的第三个星期日)。
答案 0 :(得分:2)
您只需要使用日历方法nextDate(after:)
传递工作日(星期日= 1)和月份(5月= 5)的DateComponnets
来查找5月的第一个星期日并使用在该日期之后通过星期日工作日组件找出下一个星期日的相同方法:
extension Date {
var nextSunday: Date {
return Calendar.current.nextDate(after: self, matching: DateComponents(weekday: 1), matchingPolicy: .nextTime)!
}
var nextMothersDay: Date {
return Calendar.current.nextDate(after: self, matching: DateComponents(month: 5, weekday: 1), matchingPolicy: .nextTime)!.nextSunday
}
}
Date().nextSunday // "Jan 7, 2018 at 12:00 AM"
Date().nextMothersDay // "May 13, 2018 at 12:00 AM"
答案 1 :(得分:2)
使用DateComponents
:
var dc = DateComponents()
dc.weekday = 1 // Sunday
dc.weekdayOrdinal = 2 // 2nd Sunday
dc.month = 5 // May
dc.year = 2018
let mothersDay = Calendar.current.date(from: dc)
dc.weekday = 5 // Thursday
dc.weekdayOrdinal = 4 // 4th Thursday
dc.month = 11 // November
let thanksgiving = Calendar.current.date(from: dc)
确保今天下一个母亲节的另一种方法,你可以做到:
var dc = DateComponents()
dc.weekday = 1 // Sunday
dc.weekdayOrdinal = 2 // 2nd Sunday
dc.month = 5 // May
let mothersDay = Calendar.current.nextDate(after: Date(), matching: dc, matchingPolicy: .nextTime)