Swift reading date incorrectly

喜夏-厌秋 提交于 2020-01-17 03:42:10

问题


I am working on an app where I need to store and read dates. I am finding that Swift will sometimes get the day wrong.

var testDate2 = "2016-10-11 17:00:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss Z"
let showDate2 = dateFormatter.date(from: testDate2)
let calendar = NSCalendar.current
let showDate2Components = calendar.dateComponents([.day, .month, .year], from: showDate2!)
print (showDate2!)
print (showDate2Components.day!)

print (showDate2!) produces "2016-10-11 17:00:00 +0000"

print (showDate2Components.day!) produces "12"

I am guessing this might be some sort of timezone issue but I can't figure out how to compensate for it. I want to be able to read that date as the 11th of the month not the 12th. How can I write the code so it takes the timezone from the device it is running on?

Thanks.

来源:https://stackoverflow.com/questions/40304157/swift-reading-date-incorrectly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!