2017-07-21 59 views
-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)) 
     } 

在我的情況下,如果這一天是週六週日應顯示下週,但它顯示了同一個星期。

+2

什麼「時區有關的問題」你有沒有?請顯示清楚顯示問題的[mcve]。 –

+0

@MartinR添加了一些細節 – Maddy

回答

3

你只需要拿到current week monday's date,將其添加到一個數組和地圖最後一個數組元素添加一天它:

extension Calendar { 
    static let iso8601 = Calendar(identifier: .iso8601) 
} 
extension Date { 
    var cureentWeekMonday: Date { 
     return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))! 
    } 
    var currentWeekdays: [Date] { 
     var weekdays = [cureentWeekMonday] 
     (1...4).forEach({ _ in weekdays.append(Calendar.iso8601.date(byAdding: DateComponents(day: 1), to: weekdays.last!)!) }) 
     return weekdays 
    } 
} 

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

如何顯示上一個/下一個星期? – Maddy

+0

噹噹天是星期六或星期日時,它顯示同一周,而我想顯示下一週。 – Maddy

+0

只需在當前星期幾天添加或減去一週數組元素 –

相關問題