-1

I am trying to do some math calculations in Swift and getting a bit stuck.

Essentially we get paid every 4th Friday, and I want to do a calculation that based on today's date, works out how many days until our next Pay Day.

I've got a reference day of "28/03/2008",

halfer
  • 19,824
  • 17
  • 99
  • 186
Dan
  • 25
  • 2

1 Answers1

0

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!
rmaddy
  • 314,917
  • 42
  • 532
  • 579