Search code examples
swiftfoundationdateformatter

Swift 5 - Dateformatter not working as expected


I was playing around with date formatter in swift, but the AM/PM thing is not working in my code.

import Foundation
let dtstr = "Tuesday, July 28, 2020 4:15:45 PM"
let formatter = DateFormatter()
formatter.dateFormat = "eeee, MMMM d, yyyy h:m:s a"
let date = formatter.date(from: dtstr)
print(date)

the output is this: Optional(2020-07-28 08:15:45 +0000). However, it should be 16:15:45 instead of this. Any idea why?

Thanks!


Solution

  • Date has no information about time zone, and default string representation is using a greenwich one. You can see it +0000 part in your string.

    You can get description for your own time zone like this:

    date.description(with: .current)