如何将 date/time 从 GMT 转换为本地时区

How to convert date/time from GMT to local timezone

我从 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

谢谢

输入的是格林威治标准时间的 fixed-format 日期字符串,因此 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 设置时区,以便使用用户的时区。