我从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
谢谢
最佳答案
输入是GMT格式的固定日期字符串,因此dateFormatterGet
必须具有
区域设置为“en_US_POSIX”(否则,它可以默认为用户的区域设置,比较What is the best way to deal with the NSDateFormatter locale "feechur"?),并且
时区设置为GMT(否则默认为用户的时区):
例子:
let dateFormatterGet = DateFormatter()
dateFormatterGet.locale = Locale(identifier: "en_US_POSIX")
dateFormatterGet.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
其他一切都应该正常:不要为
dateFormatterPrint
设置时区,以便使用用户的时区。关于swift - 如何将日期/时间从格林尼治标准时间转换为本地时区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57096216/