AndQ
AndQ

Reputation: 103

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 ?

Upvotes: 7

Views: 8053

Answers (2)

Abhirajsinh Thakore
Abhirajsinh Thakore

Reputation: 1822

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

Upvotes: 7

MMSousa
MMSousa

Reputation: 421

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

Upvotes: 12

Related Questions