从斯威夫特的当前日期开始下周二和周四

时间:2017-11-10 12:40:42

标签: ios swift date

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

我已经开始使用下面的解决方案,但我无法操纵这些来给我我需要的结果。有什么想法吗?

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

1 个答案:

答案 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)