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

71 Views Asked by At

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

There are 1 best solutions below

0
Eric On

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