快速转换时区之间的日期 [英] Converting date between timezones swift

查看:87
本文介绍了快速转换时区之间的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的在线服务器数据库中存有一个日期,该日期位于 GMT 中。我使用以下代码加载日期并将其转换为用户的时区:

I have a date stored on my online server database which is in GMT. I load the date and convert it to the user's timezone using the following code :

 if let messagedate = oneitem["timestamp"] as? String {
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
     let date = dateFormatter.dateFromString(messagedate)
     let source_timezone = NSTimeZone(abbreviation: "GMT")
     let local_timezone = NSTimeZone.systemTimeZone()
     let source_EDT_offset = source_timezone?.secondsFromGMTForDate(date!)
     let destination_EDT_offset = local_timezone.secondsFromGMTForDate(date!)
     let time_interval : NSTimeInterval = Double(destination_EDT_offset - source_EDT_offset!)


     let final_date = NSDate(timeInterval: time_interval, sinceDate: date!)
     curr_item.date = final_date
 }

现在我需要将日期转换回 GMT 以便将其传达给服务器,但我不知道如何将其转换回 GMT

Now I need to convert the date back to GMT in order to communicate it to the server, however I'm not sure how to convert it back to GMT.

推荐答案

难道你不能只使用你的数据格式化程序ag ain有不同的时区并转换它?例如

Couldn't you just use your data formatter again with a different time zone and convert it? Such as

dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let gmtDate = dateFormatter.dateFromString(string: "your old date as string here")

这篇关于快速转换时区之间的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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