首页 > 解决方案 > 从当前时区转换为 UTC 是不正确的 swift

问题描述

我有一个函数可以将时间从我当前的 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。

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

标签: iosswifttimensdateformatter

解决方案


尝试使用“TimeZone.current.secondsFromGMT()”,而不是执行上述所有操作,它会返回秒数,您的工作会将其转换为小时和分钟。


推荐阅读