DateFormatter returns wrong time [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-31 05:53:07

问题


I did an extension for Date that returns a formatted string:

extension Date {
    var myFormattedDate : String {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone.current
        formatter.dateFormat = "EEEE, MMMM d, y (HH:mm a)"
        return formatter.string(for: self)!
    }
}

On runtime, I set a breakpoint inside the myFormattedDate property.

po self printed:

2017-09-05 08:50:00 +0000

po formatter.string(for: self)! printed:

Tuesday, September 5, 2017 (11:50 AM)"

What could be the problem? Thanks!


回答1:


Printing a Date always returns an UTC time, regardless of the local time zone. Just avoid printing a Date object directly if you want to see the date with the proper time zone in your console.



来源:https://stackoverflow.com/questions/46048336/dateformatter-returns-wrong-time

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