Current Week Start and End Date

后端 未结 16 1383
轮回少年
轮回少年 2020-11-30 01:56

I want to get the current week start and end date and I also want to use the previous week start and end date and next week of the start and end date in current month.

16条回答
  •  天涯浪人
    2020-11-30 02:26

    Here is a solution for the swift4, we can get all the days for the current week.

    var calendar = Calendar(identifier: Calendar.Identifier.gregorian)
    let today = calendar.startOfDay(for: Date())    
    let dayOfWeek = calendar.component(.weekday, from: today) - calendar.firstWeekday
    let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
    let days = (weekdays.lowerBound ..< weekdays.upperBound)
                        .flatMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
    

提交回复
热议问题