Selçuk Yıldız
Selçuk Yıldız

Reputation: 579

Date Formatter unexpected output

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM dd, yyyy 'at' HH:mm:ss aa z"
dateFormatter.amSymbol = "AM"
let dateString = "February 02, 2022 at 10:49:06 AM GMT+3"
print(dateFormatter.date(from: dateString)!)

Prints -> 2022-02-01 21:49:06 +0000

why this prints 21:49 instead of 10:49?

Upvotes: 0

Views: 71

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

So, yes, we're both missing something. The time format should be use hh not HH (HH is for 24 hour time and some weird conversation was going in there)

So, I tested in a Playground with...

let threeHoursFromGMT = Measurement(value: 3, unit: UnitDuration.hours).converted(to: UnitDuration.seconds).value
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm:ss aa z"
dateFormatter.amSymbol = "AM"
dateFormatter.timeZone = TimeZone.init(secondsFromGMT: Int(threeHoursFromGMT))
let dateString = "February 02, 2022 at 10:49:06 AM GMT+3"
let date = dateFormatter.date(from: dateString)!
dateFormatter.string(from: dateFormatter.date(from: dateString)!)

And it generated

"Feb 2, 2022 at 6:49 PM" // let date = dateFormatter.date(from: dateString)!
"February 02, 2022 at 10:49:06 AM GMT+3" // dateFormatter.string(from: dateFormatter.date(from: dateString)!)

The first output is based on my timezone (+11) and the second is based on the formatter requirements (using +3)

Upvotes: 1

Related Questions