Skip to content

Instantly share code, notes, and snippets.

@iamjason
Created February 2, 2018 03:51
Show Gist options
  • Select an option

  • Save iamjason/c9328cef7189a59c3f9be269968b49a2 to your computer and use it in GitHub Desktop.

Select an option

Save iamjason/c9328cef7189a59c3f9be269968b49a2 to your computer and use it in GitHub Desktop.

Revisions

  1. iamjason created this gist Feb 2, 2018.
    44 changes: 44 additions & 0 deletions Date+FindPrevNextWeekday.swift
    Original 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
    }

    }