问题
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