We would like to know, whether a user system locale is using 12-hours or 24-hours format?
There are many proposed solutions at https://stackoverflow.com/q/1929958/72437
One of the solutions are
let formatString = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)!
let hasAMPM = formatString.contains("a")
However, to me, this is not a correct solution.
When I tested with de_DE
(German is using 24-hours), the returned string is HH 'Uhr'
What is Uhr mean for? I guess it mean "clock" in German?
There are so many other locales and one of them might contain letter a
.
Does anyone know, what is a correct way, to check whether user system locale is using 12-hours or 24-hours format?
I have discovered the following solution. It works great both for Taiwan and Germany as per testing. Hopefully, it works fine for other locales as well. If not, please let me know the mistake. Thank you.
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
let amSymbol: String? = dateFormatter.amSymbol
let pmSymbol: String? = dateFormatter.pmSymbol
guard let amSymbol = amSymbol, let pmSymbol = pmSymbol else {
print("24-hour format")
}
let dateAsString = dateFormatter.string(from: Date())
if dateAsString.contains(amSymbol) || dateAsString.contains(pmSymbol) {
print("12-hour format")
} else {
print("24-hour format")
}