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

1 Answer 1

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.

1
  • Thanks for the quick response.
    – Paul S.
    Jul 18, 2019 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.