簡體   English   中英

在Swift中從當前日期獲取下個星期二和星期四

[英]Get next Tuesday and Thursday from current date in Swift

我需要顯示當前日期的下一個星期二和下一個星期四的日期。 如果當前日期是星期三,那么我需要下一個星期四,然后是下周的下一個星期二。

我已經繞過以下解決方案,但是我無法操縱這些解決方案以提供所需的結果。 有任何想法嗎?

var monday: Date {
return Calendar(identifier: .iso8601).date(from: Calendar(identifier: .iso8601).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))!
}
// Monday, November 6, 2017 at 12:00:00 AM

let f = DateFormatter()
f.weekdaySymbols[Calendar.current.component(.weekday, from: Date())]
// Saturday

獲取當前工作日。 如果是星期二或星期三,則將下兩個事件的順序設置為Thu, TueThu, Tue ),否則將(3,5):

var currentDate = Date()
let calendar = Calendar.current
let currentWeekday = calendar.component(.weekday, from: currentDate)
let nextWeekdays = 3...4 ~= currentWeekday ? [5, 3] : [3, 5]

然后使用nextDate(after: matching: matchingPolicy)將工作日映射到下一個事件

let result = nextWeekdays.map { weekday -> Date in
    let components = DateComponents(weekday: weekday)
    let nextOccurrence = calendar.nextDate(after: currentDate, matching: components, matchingPolicy: .nextTime)!
    currentDate = nextOccurrence
    return nextOccurrence
}
print(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM