Schedule The Last Working Day Of The Month In Swift
An office checklist needs to appear on the last working day of each month, at 9 a.m. The office is closed on weekends and on a handful of dates supplied by the organization.
Finding the last weekday sounds close enough. Until that Friday is a holiday, we filter it out, and October disappears from the schedule. The calendar has quietly approved a month off.
The useful distinction is selecting the last date after applying exclusions. We can build that with Foundation’s Calendar.RecurrenceRule, a complete month interval, and a small amount of application policy.
Decide what “working day” means
This example uses a deliberately specific contract:
- Gregorian months in a fixed office time zone.
- Monday through Friday, excluding whole-day closures supplied by the app.
- One occurrence at 9 a.m. on the last remaining date.
- No occurrence when the entire month is closed.
Foundation does not supply our organization’s holiday calendar. The examples below use fictional office closures, not a country’s official business-day rules. A different working week, half-day closures, or regional holiday source needs a corresponding policy change.
There is a related Stack Overflow question about monthly EventKit events skipping shorter months. It has answers, including one for the last calendar date. Our problem adds office exclusions and calculates dates locally; it does not create or edit an EventKit series.
Calendar.RecurrenceRule is available from iOS 18 and macOS 15. The code here uses the current Swift 6.4 compiler.
Generate candidates inside the whole month
Bruno Scheele’s article combining dateInterval and RecurrenceRule is a useful starting point: let the calendar identify an interval, then enumerate dates within it. We’ll add the business rule after enumeration.
Use a daily recurrence to generate Monday–Friday candidates. The result we want is monthly, but the candidates are daily. Keeping those two ideas separate makes the exclusion step straightforward.
Put these declarations in one Swift file:
import Foundation
nonisolated struct WorkingMonthSchedule {
private let calendar: Calendar
private let closedDays: Set<Date>
init(timeZone: TimeZone, closures: [Date]) {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
self.calendar = calendar
self.closedDays = Set(
closures.map { calendar.startOfDay(for: $0) }
)
}
func lastOpening(inMonthContaining reference: Date) -> Date? {
guard let month = calendar.dateInterval(
of: .month, for: reference
) else {
return nil
}
let rule = Calendar.RecurrenceRule(
calendar: calendar,
frequency: .daily,
matchingPolicy: .strict,
repeatedTimePolicy: .first,
weekdays: [
.every(.monday), .every(.tuesday),
.every(.wednesday), .every(.thursday),
.every(.friday)
],
hours: [9],
minutes: [0],
seconds: [0]
)
let candidates = rule.recurrences(
of: month.start,
in: month.start..<month.end
)
var last: Date?
for candidate in candidates {
let day = calendar.startOfDay(for: candidate)
guard !closedDays.contains(day) else { continue }
last = max(last ?? candidate, candidate)
}
return last
}
}
The reference date identifies a month. It is not the lower bound of the search. Opening the preview on October 31 must still tell us which date October selected.
The half-open range includes the month’s start and excludes the next month’s start. Both the recurrence and the closure lookup use the same calendar and time zone. Apple’s calendar interval API supplies those boundaries; there is no “30 days in seconds” calculation here.
The recurrence is bounded to one month before iteration. We retain only the latest eligible candidate, so there is no need to materialize an unbounded recurrence or sort an array.
We also choose time matching explicitly. .strict skips a local time that does not exist; .first selects the first occurrence of a repeated local time. Nine in the morning avoids the usual overnight DST transition, but it is still better to state the policy than accidentally inherit one. These behaviors are described in the Foundation recurrence proposal.
Pass closures in the office’s time zone
A Date is an instant, not a date-only holiday. Our initializer treats each supplied instant as identifying a day in the office time zone and normalizes it to that day’s start.
If an API supplies a date-only string such as 2026-10-30, construct its calendar components in the office zone first. Parsing midnight UTC and then handing that instant to a Denver schedule can close October 29 instead. That is a fairly impressive bug for a ten-character string.
Here is a complete fixture using known valid date components. Add it after the type above:
nonisolated func octoberClosingDate() -> Date? {
let zone = TimeZone(identifier: "America/Denver")!
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = zone
// Known fixture: the office closes on Friday, October 30.
let closure = calendar.date(from: DateComponents(
year: 2026, month: 10, day: 30, hour: 12
))!
let reference = calendar.date(from: DateComponents(
year: 2026, month: 10, day: 31, hour: 12
))!
let schedule = WorkingMonthSchedule(
timeZone: zone,
closures: [closure]
)
return schedule.lastOpening(inMonthContaining: reference)
// October 29, 2026 at 09:00 in America/Denver.
}
The force unwraps here belong to fixed, tested fixture values. For user-entered or imported date components, validate the input and round-trip the resulting year, month, and day; calendar construction can normalize invalid components. Keep the original date-only records and zone identifier as your stored schedule policy. The normalized Date set is a calculation detail to rebuild when that policy changes.
Apply visibility filters after selection
Consider these three steps:
- Enumerate the month’s weekday candidates.
- Remove closures.
- Choose the latest remaining candidate.
If we choose the last weekday before step two, closing that date leaves no result. We have discarded all the fallback candidates too early.
The same ordering matters for UI filters. Suppose a preview ends on October 15. Don’t trim the candidate list to the preview range and then choose its last date: that would invent an October 15 month-end occurrence. Calculate October’s result using the whole month, then decide whether the selected occurrence belongs in the preview.
For an upcoming-only display, the helper below drops a selected date that has already passed. It does not reschedule it:
nonisolated func upcomingClosingDate(
schedule: WorkingMonthSchedule,
monthContaining reference: Date,
now: Date
) -> Date? {
guard let selected = schedule.lastOpening(
inMonthContaining: reference
), selected >= now else {
return nil
}
return selected
}
For a multi-month preview, evaluate each complete month in a bounded horizon and apply the display range to those results. An all-closed month stays empty; borrowing a date from the previous month would change the meaning of the schedule.
This calculation also does not arrange notification delivery or wake the app. If you use its output for reminders, manage the notification requests separately and replace affected requests when the closure policy changes.
Test the dates that would embarrass a calendar
The useful fixtures go beyond checking that the result is a Friday:
| Fixture | Expected result in the office zone |
|---|---|
| October 2026, no closures | October 30 at 09:00 |
| October 30 closed | October 29 at 09:00 |
| October 29 and 30 closed | October 28 at 09:00 |
| February 2028, no closures | February 29 at 09:00 |
| Every weekday closed | No occurrence |
| A closure on November 2 | October’s result is unchanged |
| October result requested on October 31 | Same October result; upcoming-only helper drops it |
Also check months on each side of a daylight-saving transition. The local hour stays nine while the UTC offset can change. A fixed office schedule should not move just because the phone’s owner travels; pass the office zone instead of consulting Calendar.current during each calculation. Our daily streak article covers the same distinction for recorded activity.
The exact Swift blocks were compiled with Xcode 27.0 and Swift 6.4 for iOS 18 and macOS 15 deployment targets, with warnings treated as errors and both ordinary and MainActor default isolation. Runtime checks on macOS 27.0.1 cover the fixtures above, several time zones, and comparison with an independent day-by-day calculation. Those are macOS runtime results, not a claim of execution on an iOS 18 device.
The recurrence gives us possible dates. The office policy decides which one we actually mean.