如何将日期/时间从 GMT 转换为本地时区
Posted
技术标签:
【中文标题】如何将日期/时间从 GMT 转换为本地时区【英文标题】:How to convert date/time from GMT to local timezone 【发布时间】:2019-07-18 13:54:56 【问题描述】:我从 JSON 响应中得到一个日期时间字符串,如下所示:
2019-07-18 13:39:05
这个时间是格林威治标准时间。如何将其转换为区域设置时区,在我的情况下为东部时区,节省日光。
func convertDateFormat(date:String) -> String
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateStyle = .long
dateFormatterPrint.timeStyle = .short
let date = dateFormatterGet.date(from: date)
return dateFormatterPrint.string(from: date!)
在上面的代码中,结果应该是July 18, 2019 at 9:39 AM
谢谢
【问题讨论】:
【参考方案1】:输入是 GMT 格式的固定格式日期字符串,因此dateFormatterGet
必须有
例子:
let dateFormatterGet = DateFormatter()
dateFormatterGet.locale = Locale(identifier: "en_US_POSIX")
dateFormatterGet.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
其他一切都应该没问题:您没有为dateFormatterPrint
设置时区,以便使用用户的时区。
【讨论】:
感谢您的快速回复。以上是关于如何将日期/时间从 GMT 转换为本地时区的主要内容,如果未能解决你的问题,请参考以下文章
将日期从 GMT 时区转换为本地时区——使用 ISO_OFFSET_DATE_TIME
使用时区偏移量而不是时区标识符将 GMT 时间转换为本地时间