Skip to content

Instantly share code, notes, and snippets.

@iamjason
Created February 2, 2018 03:51
Show Gist options
  • Save iamjason/c9328cef7189a59c3f9be269968b49a2 to your computer and use it in GitHub Desktop.
Save iamjason/c9328cef7189a59c3f9be269968b49a2 to your computer and use it in GitHub Desktop.
Extension that helps to find the week's previous/next weekday. e.g. if it's sunday, what was last monday's date?
/**
Extension that helps to find the week's previous/next weekday.
e.g. if it's sunday, what was last monday's date?
usage: Date().get(direction: .previous, dayName: .monday, considerToday: true)
*/
extension Date {
// weekday is in form 1...7
enum WeekDay: Int {
case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
}
enum SearchDirection {
case next
case previous
var calendarOptions: NSCalendar.Options {
switch self {
case .next:
return .matchNextTime
case .previous:
return [.searchBackwards, .matchNextTime]
}
}
}
func get(direction: SearchDirection, dayName: WeekDay, considerToday consider: Bool = false) -> Date {
let nextWeekDayIndex = dayName.rawValue
let today = self
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
if consider && calendar.component(.weekday, from: today as Date) == nextWeekDayIndex {
return today
}
var nextDateComponent = DateComponents()
nextDateComponent.weekday = nextWeekDayIndex
let date = calendar.nextDate(after: today, matching: nextDateComponent, options: direction.calendarOptions)!
return date
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment