【问题标题】:Swift Calendar.current.nextDate timeZone issuesSwift Calendar.current.nextDate timeZone 问题
【发布时间】:2019-07-03 07:20:33
【问题描述】:

我正在尝试为下一个发生的未来时间获取 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 中设置的时区?

【问题讨论】:

    标签: swift date calendar timezone


    【解决方案1】:

    我住在格林威治标准时间,在操场上运行它会产生您正在寻找的预期结果。您正在设置日期组件的时区,但我想您自己的日历(Calendar.current)设置为 EST。您需要考虑 EST 与 GMT 的偏移量以获得所需的结果

    【讨论】:

    • 日期组件的时区是否对返回的日期有0影响?
    【解决方案2】:

    看起来 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      相关资源
      最近更新 更多