【问题标题】:Confusion when converting date from GMT+1 to UTC in Swift在 Swift 中将日期从 GMT+1 转换为 UTC 时的困惑
【发布时间】:2017-04-19 03:38:37
【问题描述】:

当尝试将“2016-06-23 12:00:00”转换为 UTC 日期时,我得到“2016-06-23 10:00:00”

第一个日期是 GMT+1,我想将其转换为 UTC。如果我没记错 GMT+0 == UTC 那么 12:00 应该是 11:00 对吧?但我总是得到 10:00。为什么会这样?如何正确转换?

我在操场上和实际设备上都试过这个

这是我使用的代码:

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let datestring:String = "2016-06-23 12:00:00"

    print("1: "+datestring)

    print("2: "+convertDateToUTC(datestring))

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func convertDateToUTC(_ datestring:String) -> String {

    let dateForm = DateFormatter()
    dateForm.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateForm.timeZone = TimeZone(abbreviation: "GMT+1")

    print(TimeZone.current.abbreviation()!)

    let date = dateForm.date(from: datestring)

    dateForm.timeZone = TimeZone(abbreviation: "UTC")

    let date1 = dateForm.string(from: date!)

    return date1

}

}

输出:

1: 2016-06-23 12:00:00
GMT+1
2: 2016-06-23 10:00:00

【问题讨论】:

    标签: ios swift date utc gmt


    【解决方案1】:

    简答:"GMT+1" 替换为"GMT+01"

    "GMT+1" 不是有效的时区缩写:

     let tz = TimeZone(abbreviation: "GMT+1")
     print(tz) // nil
    

    因此,在

    dateForm.timeZone = TimeZone(abbreviation: "GMT+1")
    

    您将dateForm.timeZone 设置为nil,这意味着日期 字符串在您的默认(本地)时区中解释。

    dateForm.timeZone = TimeZone(abbreviation: "GMT+01")
    

    你会得到预期的结果。或者,创建时区 来自(数字)GMT 偏移量或其标识符:

    dateForm.timeZone = TimeZone(secondsFromGMT: 3600)
    dateForm.timeZone = TimeZone(identifier: "GMT+0100")
    

    附录(回应您的 cmets):

    TimeZone(identifier: "GMT+0100") 
    TimeZone(identifier: "Europe/Berlin")
    

    不同时区。第一个使用一小时的固定 GMT 偏移量,第二个是一个地区(在本例中为德国)的时区, 并且与 UTC 相差一或两个小时,具体取决于是否 夏令时在指定日期有效。

    【讨论】:

    • 谢谢你,确实让它工作了!让我困惑的是 TimeZone.current.abbreviation()!给我 GMT+1 而不是 GMT+01...当我现在输入 TimeZone(abbreviation: TimeZone.current.abbreviation()!) 它将无法再次工作,我该怎么办?
    • 啊哈。 :))))))))) 我认为我们还应该建议他查看时区 是什么 而不仅仅是做出假设。
    • @abcdefg 最好不要从时区缩写创建时区。如您所见,它并不总是有效。此外,还有重复的缩写和大量无效的缩写。始终使用 identifiersecondsFromGMT 初始化程序来避免这些问题。
    • @abcdefg:很抱歉,但我不知道为什么abbreviation() 返回“GMT+1”而不是“GMT+01”。但正如 rmaddy 所说,时区缩写非常模糊(这里有一些例子:blogs.msdn.microsoft.com/oldnewthing/20080307-00/?p=23183)。 – TimeZone(identifier: TimeZone.current.identifier) 应始终给出原始时区。
    • @abcdefg:“欧洲/柏林”和“GMT+01”不是同一个时区。 “Europe/Berlin”是德国的时区,2016-06-23 是夏令时。那天,与 UTC 的时差是两个小时。 – 换句话说,将“2016-06-23 12:00:00”从德国时间转换为 UTC 和将“2016-06-23 12:00:00”从 GMT+01 转换为 UTC 是两件不同的事情,你必须决定哪个适合您的应用程序。
    猜你喜欢
    • 2012-09-18
    • 2019-03-17
    • 2018-07-28
    • 2011-07-31
    • 2011-10-20
    • 2018-04-13
    • 2011-08-29
    • 1970-01-01
    • 2018-02-04
    相关资源
    最近更新 更多