我需要显示当前日期的下周二和下周四的日期。如果当前日期是星期三,那么我需要下周四,然后是下一个星期二。
我已经开始使用下面的解决方案,但我无法操纵这些来给我我需要的结果。有什么想法吗?
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
答案 0 :(得分:3)
获取当前的工作日。如果它在周二或周三将下一次出现的顺序设置为Thu, Tue
(5,3),否则(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)