I have to format the date string (UTC format) as per device locale settings. For example in India it should display as 08/09/2017 12.23 and in US it should display as 09/08/2017 12.23, Based on different region setting it should display the date format accordingly.
Format date string as per device locale settings
Asked Answered
The best approach is to not set dateFormat
, but rather set dateStyle
and timeStyle
.
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateStyle = .medium
formatter.timeStyle = .medium
let string = formatter.string(from: Date())
If none of those styles are quite correct, then, go ahead and use dateFormat
, but rather than a string literal, set dateFormat
using setLocalizedDateFormatFromTemplate(_:)
.
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.setLocalizedDateFormatFromTemplate("ddMMyyyy HH:mm")
let string = formatter.string(from: Date())
That displays 09/08/2017 19:42
for US users, 08/09/2017 19:42
for United Kingdom users, and 08.09.2017 19:42
for German users
The answer of @Rob above didn't work for me, but it showed the right direction. It turned out the formatterBehavior
of the DateFormatter
instance wasn't set properly (it defaults to behavior10_4
, and not to default
. This works for me:
let dateFormatter = DateFormatter()
dateFormatter.formatterBehavior = .default
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
let dateString = dateFormatter.string(from: Date())
© 2022 - 2024 — McMap. All rights reserved.