【问题标题】:Converting from Current TimeZone to UTC is incorrect swift [duplicate]从当前时区转换为 UTC 是不正确的 swift [重复]
【发布时间】:2018-05-18 14:29:46
【问题描述】:

我有一个函数可以将时间从我当前的 TimeZone 转换为 UTC。

static func sendFormattedTimeString(_ string: String?) -> String {
    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "HH:mm"
    dateFormatterGet.timeZone = TimeZone.current

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "HH:mm:ss"
    dateFormatterPrint.timeZone = TimeZone(identifier: "UTC")
    if let string = string,
        let date = dateFormatterGet.date(from: string) {
        return dateFormatterPrint.string(from: date)
    }
    else {
        print("There was an error decoding the string")
        return ""
    }
}

我的位置是白俄罗斯。现在是格林威治标准时间 +3。但在 UTC 中返回 +1。 例子: 我现在的时间:16:00。 UTC 返回:14:00。

有什么问题?感谢您的回答。

【问题讨论】:

  • 您的预期结果是什么?如果是 GMT +3 的 16:00,那么它是 GMT +1 的 14:00。这对我来说是正确的。
  • UTC - 它是 GTM 0。此函数需要返回 GTM 0 - 13:00。但它返回 14:00
  • 我在我的时区 +5:30 试了一下,效果很好。您是否传递了“16:00”或任何其他字符串?
  • 是的,我传递了不同的字符串。

标签: ios swift time nsdateformatter


【解决方案1】:

不要做上述所有事情,而是尝试使用 'TimeZone.current.secondsFromGMT()',它将返回秒数,您的工作会将其转换为小时和分钟。

【讨论】:

  • 谢谢。我试过这个。但我不明白为什么转换不正确。
  • 可能与夏令时有关。
猜你喜欢
  • 2014-05-09
  • 1970-01-01
  • 2013-06-16
  • 2020-02-06
  • 1970-01-01
  • 2012-11-17
  • 2022-07-06
  • 1970-01-01
  • 2021-12-07
相关资源
最近更新 更多