Swift DateFormatter returning wrong date
Asked Answered
G

2

7

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 ?

Gottfried answered 2/5, 2018 at 21:6 Comment(2)
Change HH to hh in your first date formatter since you have am/pm.Uphold
And do you really want to treat the first date string in UTC time or local time?Uphold
F
12

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

Flori answered 2/5, 2018 at 21:38 Comment(0)
B
7

I hope this would work for you:

    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)
    print(date!)

Output:-

enter image description here

Bochum answered 3/5, 2018 at 5:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.