Reputation: 35128
Have following code:
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
}
}
And I see this in console:
(lldb) po m2030
▿ 10 elements
▿ 0 : 2022-04-25 13:30:00 +0000
- timeIntervalSinceReferenceDate : 672586200.0
Why console says: 13:30:00 +0000
which in Budapest is 15:30
, though my request was show times Budapest time at 20:30
?
I am now abroad, does it matter? In Cambodia. :) +5 hour to Budapest.
Upvotes: 0
Views: 41
Reputation: 236568
What you need is to use a custom calendar using the Budapest timezone. Try like this:
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)
}
This will print:
2022-04-25 18:30:00 +0000
2022-05-02 18:30:00 +0000
2022-05-09 18:30:00 +0000
2022-05-16 18:30:00 +0000
2022-05-23 18:30:00 +0000
2022-05-30 18:30:00 +0000
2022-06-06 18:30:00 +0000
2022-06-13 18:30:00 +0000
2022-06-20 18:30:00 +0000
2022-06-27 18:30:00 +0000
Upvotes: 1