I wrote Date extensions to get Date for a specific day of the week, and here is how easy it is to use with Swift 5,
Date.today() // Oct 15, 2019 at 9:21 AM Date.today().next(.monday) // Oct 21, 2019 at 9:21 AM Date.today().next(.sunday) // Oct 20, 2019 at 9:21 AM Date.today().previous(.sunday) // Oct 13, 2019 at 9:21 AM Date.today().previous(.monday) // Oct 14, 2019 at 9:21 AM Date.today().previous(.thursday) // Oct 10, 2019 at 9:21 AM Date.today().next(.thursday) // Oct 17, 2019 at 9:21 AM Date.today().previous(.thursday, considerToday: true) // Oct 10, 2019 at 9:21 AM Date.today().next(.monday) .next(.sunday) .next(.thursday) // Oct 31, 2019 at 9:21 AM
And hereβs the extension of the date for this,
extension Date { static func today() -> Date { return Date() } func next(_ weekday: Weekday, considerToday: Bool = false) -> Date { return get(.next, weekday, considerToday: considerToday) } func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date { return get(.previous, weekday, considerToday: considerToday) } func get(_ direction: SearchDirection, _ weekDay: Weekday, considerToday consider: Bool = false) -> Date { let dayName = weekDay.rawValue let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() } assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)") let searchWeekdayIndex = weekdaysName.firstIndex(of: dayName)! + 1 let calendar = Calendar(identifier: .gregorian) if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex { return self } var nextDateComponent = calendar.dateComponents([.hour, .minute, .second], from: self) nextDateComponent.weekday = searchWeekdayIndex let date = calendar.nextDate(after: self, matching: nextDateComponent, matchingPolicy: .nextTime, direction: direction.calendarSearchDirection) return date! } }
Sandeep
source share