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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With