Search code examples
swiftswift3nsdatenscalendar

Swift - Get next date from a array of weekdays


Context

I'm making an app where I have tasks with due dates and once they are done I want to set a new due date for according to a new date according to a day of the week repeat pattern chosen by the user.

Im saving due dates as Date. Im saving the repeat pattern as Int32 (1 for Sunday, 2 for Monday, 4 for Tuesday...) but I can easily get it to an array of Strings or numbers representing each day

Problem

How do I get the next due date as Date (so I can repeat the task)?

Example

if I have a task that is completed on a Saturday and has repeat pattern of every Monday and Wednesday I want it to be set to the next Monday. If it is them completed on Monday or Tuesday I want to set the next Wednesday.

Photo of the repeat pattern choosing

Month is never selected when other days are selected. I know how to deal with the Month. The problem is just with the days of the week


Solution

  • Never use 86400 for date math, Calendar and IndexSethave powerful methods to do that:

    // Put your weekday indexes in an `IndexSet`
    let weekdaySet = IndexSet([1, 2, 4, 7]) // Sun, Mon, Wed and Sat
    
    // Get the current calendar and the weekday from today
    let calendar = Calendar.current
    var weekday =  calendar.component(.weekday, from: Date())
    
    // Calculate the next index
    if let nextWeekday = weekdaySet.integerGreaterThan(weekday) {
        weekday = nextWeekday
    } else {
        weekday = weekdaySet.first!
    }
    
    // Get the next day matching this weekday
    let components = DateComponents(weekday: weekday)
    calendar.nextDate(after: Date(), matching: components, matchingPolicy: .nextTime)