DateFormatter returns wrong time [duplicate]

2019-03-04 22:44发布

问题:

This question already has an answer here:

  • Getting date from [NSDate date] off by a few hours 3 answers

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.