【问题标题】:Get Previous, Current and Next Weeks Excluding Saturday and Sunday获取不包括周六和周日的上一周、当前和下一周
【发布时间】:2017-07-21 13:30:41
【问题描述】:

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

我的场景:

  1. 屏幕加载时应显示当前周。
  2. 在上一个按钮上单击 (DisplayedWeek - 1)
  3. 在 Next 按钮上单击 (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】:

您可以获取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"]

【讨论】:

  • 如何显示上/下周?
  • 当今天是星期六或星期日时,它显示同一周,而我想显示下周。
  • 对当前星期几的数组元素只加或减一周
  • 您应该将所有额外信息添加到问题中。只需添加一个条件 if weekday > friday 你得到下周。
  • 好的,谢谢,先生。使用let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" for date in currentWeekdays { print(formatter.string(from: date)) } 解决了我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2017-09-16
相关资源
最近更新 更多