Home > Software engineering >  How to find the next weekday or weekend using swift?
How to find the next weekday or weekend using swift?

Time:11-02

I found this old post regarding how to find the next Monday, Tuesday... etc. This is helpful, but what if we want to find next weekday or weekend? The next weekend might be Saturday, or it might be Sunday, so now what should I do to let the code decide for us? (That goes similarly to find the next weekday, which has 5 choices based on the current date).

Any help would work. Is there a way to modify the existing extension I mentioned before in the old post?

CodePudding user response:

Finding the date for the next weekend is simple.

let now = Date()
if let timeInterval = cal.nextWeekend(startingAfter: now, direction: .forward) {
    let startDate = timeInterval.start
    let endDate = timeInterval.end
    print(startDate, endDate)
}

nextWeekend(startingAfter:direction:) does not return a specific Date object. It returns a DateInterval object, instead.

Finding the next date for any of week days is a challenge. That's because it can be Monday, Tuesday, Wednesday, Thursday or Friday. The following is how to find the next Monday.

let cal = Calendar.current
var comps = DateComponents()
comps.weekday = 2
let now = Date()
if let nextMonday = cal.nextDate(after: now, matching: comps, matchingPolicy: .nextTimePreservingSmallerComponents) {
    print(nextMonday)
}

, where 2 is for Monday.

  • Related