'How to get date matching a particular time in a given time zone - Swift

How can I get a Date object that matches a given time in a given time zone?

For example, I want to get the Date that represents the next 3AM CST.

I thought of this, but I'm not sure if it's the best way (if it even works at all). I also don't know if it generates the next soonest date that matches the given data components. The Apple docs are a little unclear on this.

let calendar = Calendar(identifier: .gregorian)
let timeZone = TimeZone(abbreviation: "CDT")
let dateComponents = DateComponents(calendar: calendar, timeZone: timeZone, hour: 3)
let date3AM = calendar.date(from: dateComponents)


Solution 1:[1]

In fact, there is an easier way.

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: "CDT")!
let dateFor3AmCst = calendar.nextDate(after: Date.now, matching: DateComponents(hour: 3), matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .forward)!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric