1

I'm getting a date time string from a JSON response that looks like this:

2019-07-18 13:39:05

This time is GMT. How can I convert this to locale time zone, in my case Eastern with day light savings.

func convertDateFormat(date:String) -> String {

    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateStyle = .long
    dateFormatterPrint.timeStyle = .short

    let date = dateFormatterGet.date(from: date)

    return dateFormatterPrint.string(from: date!)

}

In the code above the result should be July 18, 2019 at 9:39 AM

Thanks

Paul S.
  • 1,342
  • 4
  • 22
  • 43

1 Answers1

1

The input is a fixed-format date string in GMT, therefore dateFormatterGet must have

Example:

let dateFormatterGet = DateFormatter()
dateFormatterGet.locale = Locale(identifier: "en_US_POSIX")
dateFormatterGet.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

Everything else should be OK: you don't set a time zone for dateFormatterPrint so that the user's time zone is used.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382