In order to calculate the next 4th Friday of the month, you need a combination of the right DateComponents
and Calendar
.
// The 4th Friday at noon
let payDayComps = DateComponents(hour: 12, weekday: 6, weekdayOrdinal: 4)
// Given the current date, calculate the next 4th Friday at noon
let nextPayDay = Calendar.current.nextDate(after: Date(), matching: payDayComps, matchingPolicy: .nextTime)
You don't need a past reference date for this if your goal is to get the next 4th Friday based on today's date. Change the value of the after
parameter if you need to calculate the 4th Friday based on some other specific date.
If this is run on the 4th Friday of a month then it will return today's date if run before noon and it will return the 4th Friday of the next month if run after noon. Change the hour value in payDayComps
if you want different results (such as 0
for midnight).
To calculate the number of days until that next pay day you can do:
let daysToPayDay = Calendar.current.dateComponents([.day], from: Date(), to: nextPayDay).day!