Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date string as per device locale settings

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.

like image 351
Warrior Avatar asked Dec 11 '22 10:12

Warrior


1 Answers

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

like image 138
Rob Avatar answered Dec 31 '22 17:12

Rob