获取上周六和周日的上周,下周和下周

问题描述 投票:0回答:1

我希望显示星期一到星期五的日期/天,不包括星期六/星期日,如下图所示。

enter image description here

我的场景:

  1. 屏幕加载时,应显示当前周。
  2. 在上一个按钮单击(DisplayedWeek - 1)
  3. 在“下一步”按钮上单击(DisplayedWeek + 1)。

我的工作,

经过一些研究,这是我尝试过的。

        let calendar = Calendar.current

        let currentDate = calendar.startOfDay(for: Date())

        /* value =  0 for current,
           value =  1 for next,
           value = -1 for previous week.

        */
        let nextWeek:Date =  calendar.date(byAdding: .weekOfMonth, value: 1, to: currentDate)! as Date

        let dayOfWeek = calendar.component(.weekday, from: nextWeek)
        let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: nextWeek)!

        let days = (weekdays.lowerBound ..< weekdays.upperBound).flatMap {

            calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: nextWeek)

        }.filter { !calendar.isDateInWeekend($0) }

        // Week Days from monday to friday
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"

        for date in days {
            print(formatter.string(from: date))
        }

在我的情况下,如果这一天是星期六或星期日,它应该显示在下周,但它显示在同一周。

ios swift nsdateformatter
1个回答
4
投票

你可以得到current week monday's date,只需添加n天:

Swift 4.1•Xcode 9.3或更高版本

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"]
© www.soinside.com 2019 - 2024. All rights reserved.