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

时间:2016-12-21 23:37:45

标签: swift date nsdate nsdateformatter

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

OR

我希望dateString以这种格式"2016-12-22T08:00",当用户时间是UTC或{{1用户时间是UTC时间00:00

当我尝试下面的代码并打印dateObject时,它会打印2016-12-22 21:30:00 +0530,但我希望2016-12-22 16:00:00 +0000,因为我的当地时间是UTC的+05:30。

Optional(2016-12-22 02:30:00 +0000)

1 个答案:

答案 0 :(得分:2)

dateFormat修复为:

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

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

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

现在你的代码工作正常。

“但等等,print(dataObject)的输出不是我想要的”

是的。就像你之前的成千上万,你误解了打印Date对象的输出。

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

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

你得到你想要的东西。

相关问题