如何计算每月的第 N 个工作日(例如:母亲节)
How to Calculate Nth Weekday of Month (example: Mother's Day)
只是在寻找一个简单的解决方案来以编程方式确定诸如母亲节(五月的第二个星期日)或父亲节(六月的第三个星期日)之类的事情。
您只需使用日历方法 nextDate(after:)
传递工作日(星期日 = 1)和月份(五月 = 5)的 DateComponnets
即可找出五月的第一个星期日和使用相同的方法找出该日期之后的下一个星期日,仅传递星期日工作日部分:
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"
使用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)
只是在寻找一个简单的解决方案来以编程方式确定诸如母亲节(五月的第二个星期日)或父亲节(六月的第三个星期日)之类的事情。
您只需使用日历方法 nextDate(after:)
传递工作日(星期日 = 1)和月份(五月 = 5)的 DateComponnets
即可找出五月的第一个星期日和使用相同的方法找出该日期之后的下一个星期日,仅传递星期日工作日部分:
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"
使用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)