-1

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!

Sushi Bear
  • 53
  • 1
  • 5
  • 2
    `08:15:45` in London _is_ `16:15:45` where you are. The world is round so different places call the same moment by different times. – matt Sep 10 '21 at 15:43
  • 1
    Also note that the output of your `print` statement is _not formatted_ so what you say in your DateFormatter is totally irrelevant. – matt Sep 10 '21 at 15:45
  • Thanks :-) I now understand the problem :-) – Sushi Bear Sep 10 '21 at 23:42

1 Answers1

0

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)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220