本文介绍了获取上周六和周日的上周,下周和下周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的情景:


  1. 当屏幕加载时,应显示当前周。

  2. 点击上一个按钮( DisplayedWeek - 1

  3. 点击下一步按钮( DisplayedWeek + 1 )。

  1. When screen loads the current week should display.
  2. On previous button click (DisplayedWeek - 1)
  3. On Next button click (DisplayedWeek + 1).

我的工作

经过一番研究后,这就是我的尝试。

After some research this is what i have tried.

        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))
        }

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

In my case if the day is Saturday or Sunday it should display next week but it is displaying the same week.

推荐答案

你只需要得到,将其添加到数组并映射最后一个数组元素,向其添加一天:

You just need to get the current week monday's date, add it to an array and map the last array element adding one day to it:

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"]

这篇关于获取上周六和周日的上周,下周和下周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:42