简体   繁体   English

如何获取与给定时区中特定时间匹配的日期 - Swift

[英]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?如何获取与给定时区中给定时间匹配的Date对象?

For example, I want to get the Date that represents the next 3AM CST.例如,我想获取代表下一个 3AM CST 的Date

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM