简体   繁体   English

迅速在格林尼治标准时间获取两个日期之间的差额

[英]Swift get difference between two dates in GMT

I recently noticed strange behaviour trying to find the difference between two dates (in seconds). 最近,我发现尝试查找两个日期(以秒为单位)之间的差异的奇怪行为。

I have a datestring that is in GMT time: 我有一个格林尼治标准时间的日期字符串:

2016-01-07 01:09:47.289000

I want to find how many seconds since that time NOW. 我想找到从现在开始的多少秒。

But I notice that when I use NSDate() I get the time of my local time, not GMT time. 但是我注意到,当我使用NSDate()时,我得到的是本地时间,而不是GMT时间。

How would I go about doing this? 我将如何去做呢?

Use the NStimeZone class to set time zone 使用NStimeZone类设置时区

let date = NSDate()
var formatter = NSDateFormatter()
let gmt = NSTimeZone(abbreviation: "GMT")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = gmt
formatter.stringFromDate(date)

To compare, convert the current date from NSDate to "GMT" and then calculate the time interval between the two. 为了进行比较,请将当前日期从NSDate转换为“ GMT”,然后计算两者之间的时间间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM