我正在尝试获取下一个发生的 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/