我希望将此格式的 dateString "2016-12-22T08:00:00-08:00"
转换为用户本地时间的日期对象,例如 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 起协调世界时
当我尝试下面的代码并打印 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
现在您的代码可以正常工作了。
“等等,print(dataObject)
的输出不是我想要的”
是的。与您之前的数千人一样,您误解了打印 Date
对象的输出。
如果您希望以给定的格式查看本地时区的Date
,请使用DateFormatter
将Date
转换为字符串
。默认情况下,您将获得当前的本地时区。
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
let newString = dateFormatter.string(from: dateObject)
print(newString)
你得到的正是你想要的。
关于swift - 将一个时区的日期字符串转换为本地时间 Swift 中的日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41273690/