有以下代码:
let start = DateComponents(calendar: .current, year: 2022, month: 4, day: 25).date!
let end = DateComponents(calendar: .current, year: 2022, month: 7, day: 2).date!
let dateInterval: DateInterval = .init(start: start, end: end)
let m2030 = dateInterval.dates(matching: .init(calendar: .current, timeZone: TimeZone(identifier: "Europe/Budapest"), hour: 20, minute: 30, weekday: 2))
extension DateInterval {
func dates(matching components: DateComponents) -> [Date] {
var start = self.start
var dates: [Date] = []
while let date = Calendar.current.nextDate(after: start, matching: components, matchingPolicy: .strict), date <= end {
dates.append(date)
start = date
}
return dates
}
}
我在控制台上看到了这个:
(lldb) po m2030
▿ 10 elements
▿ 0 : 2022-04-25 13:30:00 +0000
- timeIntervalSinceReferenceDate : 672586200.0
为什么控制台说:13:30:00 +0000
在布达佩斯是15:30
,尽管我的请求是在20:30
显示布达佩斯时间?
我现在在国外,有关系吗?在柬埔寨。:(+5小时到达布达佩斯。
您需要的是使用布达佩斯时区的自定义日历。尝试如下:
extension DateInterval {
func dates(matching components: DateComponents, using calendar: Calendar = .current) -> [Date] {
var start = self.start
var dates: [Date] = []
while let date = calendar.nextDate(after: start, matching: components, matchingPolicy: .strict), date <= end {
dates.append(date)
start = date
}
return dates
}
}
var budapestCalendar = Calendar(identifier: .iso8601)
budapestCalendar.timeZone = TimeZone(identifier: "Europe/Budapest")!
let start = DateComponents(calendar: budapestCalendar, year: 2022, month: 4, day: 25).date!
let end = DateComponents(calendar: budapestCalendar, year: 2022, month: 7, day: 2).date!
let dateInterval: DateInterval = .init(start: start, end: end)
let m2030 = dateInterval.dates(matching: .init(hour: 20, minute: 30, weekday: 2), using: budapestCalendar)
for date in m2030 {
print(date)
}
这将打印:
2022-04-25 18:30:00+0000
2022-05-02 18:30:0k+0000
2022-05-16 18:30:0+0000
22022-05-23 18:30:000
2022-05-30 18:30:0000
2022-06-06 18:300:00+0000
2022-06-13 18:30:0:00+0000
2022-06-20 18:30:00+0000
2022-06-27 18:30:0+0000