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

标签 swift date nsdate nsdateformatter

我希望将此格式的 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,请使用DateFormatterDate 转换为字符串。默认情况下,您将获得当前的本地时区。

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/

相关文章:

ios - 如何让 Voiceover 拼出单词中的每个字母?

Swift - SpriteKit - 在永远运行时更新 SKAction.waitForDuration

swift - 如何在 RealmSwift 中正确使用 shouldCompactOnLaunch

swift - Swift 3 中 AVCaptureSession 到 UIImage 的错误

c# - WPF Datepicker - SelectedDate 只是日期而不是时间

objective-c - 有没有一种简单的方法可以将 ISO8601 时间戳转换为格式化的 NSDate?

java - 转换字符串值时对使用 SimpleDateFormat 感到困惑

mysql - 一年中从星期六开始的一周

ios - 如何将 "today"(NSDate) 与格式化字符串日期 (dd/MM/yyyy) 进行比较?

ios - 尝试将日期选择器时间与当前时间ios进行比较