How to get Monday's date of the current week in swift

前端 未结 8 1754
死守一世寂寞
死守一世寂寞 2020-11-29 05:36

I\'m trying to get Monday\'s date of the current week. This is treated as the first day of the week in my table view. I also need to get Sunday\'s of the current week. This

8条回答
  •  情话喂你
    2020-11-29 05:54

    Here's a simplified version of Sandeep's answer.

    Usage:

    Date().next(.monday)
    Date().next(.monday, considerToday: true)
    Date().next(.monday, direction: .backward)
    

    Extension:

    public func next(_ weekday: Weekday,
                     direction: Calendar.SearchDirection = .forward,
                     considerToday: Bool = false) -> Date
    {
        let calendar = Calendar(identifier: .gregorian)
        let components = DateComponents(weekday: weekday.rawValue)
    
        if considerToday &&
            calendar.component(.weekday, from: self) == weekday.rawValue
        {
            return self
        }
    
        return calendar.nextDate(after: self,
                                 matching: components,
                                 matchingPolicy: .nextTime,
                                 direction: direction)!
    }
    
    public enum Weekday: Int {
        case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
    }
    

提交回复
热议问题