gpt4 book ai didi

ios - 从 Swift 中的当前日期获取下周二和周四

转载 作者:搜寻专家 更新时间:2023-11-01 06:15:00 25 4
gpt4 key购买 nike

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

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

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

关于ios - 从 Swift 中的当前日期获取下周二和周四,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47223014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com