I have to present time trackings summary for specific payroll frequency periods: monthly, weekly, biweekly. I did find a way to get start date and end date for current week or current month ex.
var startOfMonth: Date? {
let components = Calendar.current.dateComponents([.year, .month], from: startOfDay)
return Calendar.current.date(from: components)
}
var endOfMonth: Date? {
guard let startOfTheMonth = startOfMonth else { return nil }
var components = DateComponents()
components.month = 1
components.second = -1
return Calendar.current.date(byAdding: components, to: startOfTheMonth)
}
But how can I get those dates for current biweekly period?
I assume that biweekly periods (it is 26 paychecks a year) are every two weeks since start of current year: ex. 1st biweek is 1-2 week of the 2020 year is 1.01.20-12.01.20; 24th biweek is 47-48 week is 16.11.20-29.11.20 and last 26th biweek is 51-53 week is 14.12.20-31.12.20.
EDIT:
Based on @Leo Dabus answer I managed to get startOfBiweek and endOfBiweek. Thank you!
var startOfBiweek: Date? {
let biweekIntervals = biweekIntervalsInSameYear(using: .iso8601)
return biweekIntervals.first(where: { $0.contains(self)})?.start
}
var endOfBiweek: Date? {
let biweekIntervals = biweekIntervalsInSameYear(using: .iso8601)
return biweekIntervals.first(where: { $0.contains(self)})?.end
}
I don't know if there is an easier way to accomplish what you want but this is what I came up with. First I get all days in the same year. Then I create an array with 26 subarrays and group dates for every 2 weeks. Then I create an array of date intervals using the first and last date of each subarray.
This will print:
Another approach, this one seems shorter but I recommend testing it further: