Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get next Tuesday and Thursday from current date in Swift

Tags:

date

ios

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
like image 741
Ben Sullivan Avatar asked Nov 10 '17 12:11

Ben Sullivan


1 Answers

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)
like image 96
vadian Avatar answered Oct 20 '22 12:10

vadian