Created
February 2, 2018 03:51
-
-
Save iamjason/c9328cef7189a59c3f9be269968b49a2 to your computer and use it in GitHub Desktop.
Revisions
-
iamjason created this gist
Feb 2, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,44 @@ /** 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 } }