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

发布于 2025-01-31 19:36:22 字数 428 浏览 2 评论 0原文

如何获得与给定时区中给定时间匹配的date对象?

例如,我想获得代表下一个CST的date

我想到了这一点,但是我不确定这是否是最好的方法(如果它根本无法使用)。我也不知道它是否会生成与给定数据组件相匹配的下一个最早日期。苹果文档对此有些不清楚。

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)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月苍老的讽刺 2025-02-07 19:36:22

实际上,有一种更简单的方法。

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

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)!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文