Reputation: 1448
Question is rather simple. I'm trying to figure how to tell what time format the current device is in. I'm assuming its something simple like with languages -> Local.current.languageCode. When I search I keep getting results for conversions.
Upvotes: 0
Views: 92
Reputation: 543
Although the feature wasn't available when you asked, since iOS 16 and macOS 13 you can also look at the current Locale's hourCycle
value:
if Locale.current.hourCycle == .oneToTwelve
|| Locale.current.hourCycle == .zeroToEleven {
...
}
Note there are not 2, but instead 4 different possibilities (0-11, 1-12, 0-23, 1-24). The 0- vs 1- distinctions are important between between midnight and 1am, and again between noon and 1pm. For instance, one minute after midnight could be written four ways: 0:01, 0:01am, 12:01am, and 24:01. See Apple's docs, or the Unicode Common Locale Data Repository definitions for HourCycle
at https://www.unicode.org/reports/tr35/#UnicodeHourCycleIdentifier .
And, although this value is coming from the Locale, it does reflect any 12/24-hour time preference the user may have set. (At least it does when you query Locale.current
)
Upvotes: 1
Reputation: 236498
You can create a date format from a template passing "j"
and .current
locale. If the resulting format contains the letter "a"
means that the date format for that specific locale is set to 12 hours:
extension Locale {
var is24Hour: Bool {
DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: self)?.contains("a") == false
}
}
Playground testing:
if Locale.current.is24Hour {
print("Current setting is 24h")
} else {
print("Current setting is 12h")
}
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
print(dateFormatter.string(from: Date()))
This will print:
Current setting is 12h
10:09 PM
Upvotes: 3