在Swift中将日期从GMT + 1转换为UTC时出现混乱 [英] Confusion when converting date from GMT+1 to UTC in Swift

查看:301
本文介绍了在Swift中将日期从GMT + 1转换为UTC时出现混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将2016-06-23 12:00:00转换为UTC日期时,我会收到2016-06-23 10:00:00

When trying to convert "2016-06-23 12:00:00" to a UTC Date I get "2016-06-23 10:00:00"

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

The first Date is in GMT+1 which I want to convert to UTC. If I'm not mistaken GMT+0 == UTC so 12:00 should be 11:00 right? But I always get 10:00. Why is that the case and how do I convert it correctly?

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

I both tried this in the playground and on an actual device

这是我使用的代码:

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


推荐答案

简答:替换GMT + 1GMT + 01

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

"GMT+1" is not a valid time zone abbreviation:

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

因此,在

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

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

you set dateForm.timeZone to nil, which means that the date string is interpreted in your default (local) timezone.

使用

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

您将获得预期的结果。或者,从(数字)GMT偏移或其标识符创建时区

you'll get the expected result. Alternatively, create the time zone from the (numerical) GMT offset or from its identifier:

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






附录(以回应您的评论):


Addendum (in response to your comments):

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

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

are different time zones. The first one uses a fixed GMT offset of one hour, the second one is the time zone in a region (in this case, Germany), and differs from UTC by one or two hours, depending on whether daylight saving time is active at the specified date.

这篇关于在Swift中将日期从GMT + 1转换为UTC时出现混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆