Get Previous, Current and Next Weeks Excluding Saturday and Sunday

后端 未结 1 1016
旧巷少年郎
旧巷少年郎 2020-12-20 09:32

I wants to display dates/days from Monday to Friday excluding Saturday/Sunday as mentioned in the image below.

相关标签:
1条回答
  • 2020-12-20 09:52

    You can get the current week monday's date, and just add n days to it:

    Swift 4.1 • Xcode 9.3 or later

    extension Calendar {
        static let iso8601 = Calendar(identifier: .iso8601)
    }
    extension Date {
        var cureentWeekMonday: Date {
            return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
        }
        var currentWeekdays: [Date] {
            return (0...4).compactMap{ Calendar.iso8601.date(byAdding: DateComponents(day: $0), to: cureentWeekMonday) } // for Swift versions earlier than 4.1 use flatMap instead
        }
    }
    

    let currentWeekdays = Date().currentWeekdays
    print(currentWeekdays)  // ["Jul 17, 2017, 12:00 AM", "Jul 18, 2017, 12:00 AM", "Jul 19, 2017, 12:00 AM", "Jul 20, 2017, 12:00 AM", "Jul 21, 2017, 12:00 AM"]
    
    0 讨论(0)
提交回复
热议问题