Swift Calendar.current.nextDate 时区问题

标签 swift date calendar timezone

我正在尝试获取下一个发生的 future 时间的 Date 对象,其中 UTC 时间的小时数为 18。但是我的代码无法按预期工作。我有以下内容:

let dateComponents = DateComponents(timeZone: TimeZone(abbreviation: "GMT"), hour: 18)
let date = Calendar.current.nextDate(after: Date(), matching: dateComponents, matchingPolicy: .nextTime)

print(date)

问题是这会导致 2019-02-09 23:00:00 +0000

该日期是下一次发生的时间,其中 EST 的 18 点。

由于 dateComponents 将时区设置为 UTC,小时设置为 18,因此我预计日期将为 2019-02-09 18:00:00 + 0000 。此外,更改时区似乎对找到的 nextDate 没有影响。

为什么 nextDate 函数不遵循传递给它的 dateComponents 中设置的时区?

最佳答案

看起来 DateComponents 中的时区被忽略了。 但是,当您在新日历中设置时区时,您会得到正确的结果。

let dateComponents = DateComponents(hour: 18)
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!

let date = calendar.nextDate(after: Date(), matching: dateComponents, matchingPolicy: .nextTime)

print(date) // Optional(2020-09-29 18:00:00 +0000)

关于Swift Calendar.current.nextDate 时区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54602750/

相关文章:

swift - UIScrollView 导致 "Misplaced Views"AutoLayout 问题

iOS 10,swift 4.1,将 View 的顶部 anchor 设置为 topLayoutGuide 底部 anchor 导致冲突

java - 以年、月、日、小时、分钟和秒为单位计算年龄

java - 出生日期是什么 Java 数据类型?

php - 使用 PHP 创建 MongoDB 的 ISODate

c - 用 C 语言构建日历程序的开始步骤的建议

swift - 当有人使用 Swift 设置 pin 时,实现自定义 MKAnnotationView 的最佳方法是什么?

swift - 将 JSON 解析为可用格式

android - 使用 android api 创建新的同步日历

Java计算一年中的天数,或两个日期之间的天数