Ben Sullivan
Ben Sullivan

Reputation: 2154

Get next Tuesday and Thursday from current date in Swift

I need to display the dates of the next Tuesday and the next Thursday from the current date. If the current date is Wednesday then I would need the next Thursday and then the next Tuesday the following week.

I've gone around in circles with solutions like the below but I haven't been able to manipulate these to give me the results I need. Any ideas?

var monday: Date {
return Calendar(identifier: .iso8601).date(from: Calendar(identifier: .iso8601).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))!
}
// Monday, November 6, 2017 at 12:00:00 AM

and

let f = DateFormatter()
f.weekdaySymbols[Calendar.current.component(.weekday, from: Date())]
// Saturday

Upvotes: 8

Views: 3204

Answers (1)

vadian
vadian

Reputation: 285082

Get the current weekday. If it's Tuesday or Wednesday set the order of the next both occurrences to Thu, Tue (5, 3) otherwise (3, 5):

var currentDate = Date()
let calendar = Calendar.current
let currentWeekday = calendar.component(.weekday, from: currentDate)
let nextWeekdays = 3...4 ~= currentWeekday ? [5, 3] : [3, 5]

Then map the weekdays to the next occurrences with nextDate(after: matching: matchingPolicy)

let result = nextWeekdays.map { weekday -> Date in
    let components = DateComponents(weekday: weekday)
    let nextOccurrence = calendar.nextDate(after: currentDate, matching: components, matchingPolicy: .nextTime)!
    currentDate = nextOccurrence
    return nextOccurrence
}
print(result)

Upvotes: 10

Related Questions