Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift DateFormatter returning wrong date

I have a issue with getting the correct date in the following case

let dateString = "May 2, 2018 at 3:31 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy 'at' HH:mm a"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let date = dateFormatter.date(from: dateString)!

I am getting "May 2, 2018 at 8:31 AM" as the date, which is wrong

When the same date is used with a different dateformatting string i get the correct date

let dateFormatter3 = DateFormatter()
dateFormatter3.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter3.locale = Locale(identifier: "en_US_POSIX")
dateFormatter3.timeZone = TimeZone(identifier: "UTC")
let date3 = dateFormatter3.date(from: "2018-05-02T15:31:00")!

Date returned is "May 2, 2018 at 11:31 AM" which is correct.

I like to know what i am doing wrong in the first code block? Or is this a bug in the date formatter class ?

like image 978
AndQ Avatar asked Dec 18 '22 23:12

AndQ


1 Answers

when hour is in am/pm(1~12) use hh, to hour in day(0~23) use HH.

This helps me format my dates: enter image description here

like image 126
MMSousa Avatar answered Feb 01 '23 22:02

MMSousa