将一个时区的日期字符串转换为本地时间的日期对象Swift

Convert date string of one time zone to date object in local time Swift

我希望将此格式 "2016-12-22T08:00:00-08:00" 中的 dateString 转换为用户本地时间的日期对象,例如 2016-12-22 21:30:00 +0530 当用户时间是 UTC 的 +05:30 时

我想要这种格式的 dateString "2016-12-22T08:00" 将 PST 时间转换为用户本地时间的日期对象,例如 2016-12-22 21:30:00 +0530 当用户时间是来自 UTC 的 +05:30 或 2016-12-22 16:00:00 +0000 当用户时间是 00:00 来自 UTC

当我尝试下面的代码并打印 dateObject 时,它打印 Optional(2016-12-22 02:30:00 +0000) 但我想要 2016-12-22 21:30:00 +0530 因为我的本地时间是 UTC 的 +05:30。

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-08:00"
dateFormatter.timeZone = NSTimeZone.local

let dateString = "2016-12-22T08:00:00-08:00"
let dateObject = dateFormatter.date(from: dateString)
print("dateObject \(dateObject1)")

将您的 dateFormat 修正为:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"

删除 timeZone 行。不需要,因为您的日期字符串指定了自己的时区。

dateFormatter.timeZone = NSTimeZone.local // remove this line

现在您的代码可以正常工作了。

"But wait, the output of print(dataObject) isn't what I want"

是的。与之前的数千人一样,您误解了打印 Date 对象的输出。

如果您希望以给定的格式在当地时区查看 Date,请使用 DateFormatterDate 转换为 String。默认情况下,您将获得当前的本地时区。

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
let newString = dateFormatter.string(from: dateObject)
print(newString)

你得到你想要的。