Search code examples
iosswiftdatedatetimensdateformatter

Dateformatter issue in swift


My API sending me date string in UTC like 2/20/2016 11:45 AM. For displaying date in my timezone, I am converting date from UTC to Local time zone like below code

    let sourceDateString = "12/20/2016 11:45 AM"
    let formatter = DateFormatter()
     formatter.dateFormat = "MM/dd/yyyy hh:mm a"
     formatter.timeZone = TimeZone(identifier: "UTC")
     let date = formatter.date(from: sourceDateString)

     print(date)

     formatter.timeZone = NSTimeZone.local
     formatter.dateFormat = "MMM dd,yyyy hh:mm a"

     let strDate = formatter.string(from: date!)
     print(strDate)

Above code is working fine if my device time format is in 12 HR but if I am using 24 Hr date from my device then above code is not working. Event it's not able to convert UTC string to date.

Please check above code in the device, it's working fine in simulator.


Solution

  • With help of @Martin R, Following code worked for me.

        let sourceDateString = "12/20/2016 11:45 AM"
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yyyy hh:mm a"
        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.locale = Locale(identifier: "en_US_POSIX")
        let date = formatter.date(from: sourceDateString)
    
        print(date)
    
        formatter.timeZone = NSTimeZone.local
        formatter.dateFormat = "MMM dd,yyyy hh:mm a"
    
        let strDate = formatter.string(from: date!)
        print(strDate)
    

    I forgot to add "POSIX".