0

The backend provides me with date in the format: "2018-09-07 01:00:00 am" The timezone of this date is UTC. Now I have to convert it into local timezone. The function I am using is:

func getLocalDate(dateString: String) -> String {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss a"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    dateFormatter.locale = Locale.current

    let dt = dateFormatter.date(from: dateString)

    dateFormatter.timeZone = TimeZone.current
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss aZ"

    return dateFormatter.string(from: dt!)

}

With this, the date is being converted into UTC first and then into local timezone so I don't get the desired result. How do I set the timezone of that date as UTC, without any conversion?

EDIT: The output i am getting is 2018-09-07 05:45:00 AM+0545 but the expected output is 2018-09-07 06:45:00 AM+0545

Sujal
  • 1,447
  • 19
  • 34
  • What result do you get, and what is the expected result? What time zone are you int? – Martin R Sep 07 '18 at 10:58
  • Remove `dateFormatter.locale = Locale.current` at the time of UTC date creation. – Pratik Sodha Sep 07 '18 at 11:19
  • You want `hh` not `HH` for 12 hour time with am/pm. `HH` is for 24 hour time – Paulw11 Sep 07 '18 at 11:27
  • You can concat +0000 to the received string and convert the resulting string to date using "yyyy-MM-dd HH:mm:ss a Z" date format. Attention, at this step you don't need to set the timezone and local of your date formatter. The second step still valid. – Mourad Brahim Sep 07 '18 at 11:28
  • The problem here is that `TimeZone(abbreviation: "UTC")` in fact means that your time from the server should be: `2018-09-07 01:00:00 am+0100`. Passing `2018-09-07 01:00:00 am` you mean "2018-09-07 01:00:00 am+0000" for date formatter – lobstah Sep 07 '18 at 11:31
  • Locale should be set to en_US_POSIX – Leo Dabus Sep 07 '18 at 11:52
  • Changing HH to hh as suggested by @Paulw11 worked. – Sujal Sep 11 '18 at 11:40

1 Answers1

0

The format specifier for 12 hour time is hh, not HH which is for 24 hour time.

Combining HH with an am/pm specifier a will give an incorrect result.

Paulw11
  • 108,386
  • 14
  • 159
  • 186