Swift (3.x) Version von beiden beliebtestenen Lösungen in Form von Datum Erweiterung:
extension Date {
static var is24HoursFormat_1 : Bool {
let dateString = Date.localFormatter.string(from: Date())
if dateString.contains(Date.localFormatter.amSymbol) || dateString.contains(Date.localFormatter.pmSymbol) {
return false
}
return true
}
static var is24HoursFormat_2 : Bool {
let format = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.autoupdatingCurrent)
return !format!.contains("a")
}
private static let localFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale.autoupdatingCurrent
formatter.timeStyle = .short
formatter.dateStyle = .none
return formatter
}()
}
Verbrauch:
Date.is24HoursFormat_1
Date.is24HoursFormat_2
Swift (2.0) Version von beiden beliebtestenen Lösungen in Form von NSDate Erweiterung:
extension NSDate {
class var is24HoursFormat_1 : Bool {
let dateString = NSDate.localFormatter.stringFromDate(NSDate())
if dateString.containsString(NSDate.localFormatter.AMSymbol) || dateString.containsString(NSDate.localFormatter.PMSymbol) {
return false
}
return true
}
class var is24HoursFormat_2 : Bool {
let format = NSDateFormatter.dateFormatFromTemplate("j", options: 0, locale: NSLocale.autoupdatingCurrentLocale())
return !format!.containsString("a")
}
private static let localFormatter : NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.autoupdatingCurrentLocale()
formatter.timeStyle = .ShortStyle
formatter.dateStyle = .NoStyle
return formatter
}()
}
Bitte beachten Sie, dass Apple sagt folgende auf NSDateFormatter (Date Formatters):
ein Datum Formatierer zu erstellen ist kein billiger Betrieb. Wenn Sie wahrscheinlich häufig einen Formatierer verwenden, ist es normalerweise effizienter, eine einzelne Instanz im Cache zwischenzuspeichern, als mehrere Instanzen zu erstellen und zu verwerfen. Ein Ansatz besteht darin, eine statische Variable zu verwenden.
Das ist der Grund für die statische lassen
Zweitens sollten Sie NSLocale.autoupdatingCurrentLocale() verwenden (für is24HoursFormat_1), auf diese Weise werden Sie immer den aktuellen aktuellen Zustand erhalten.
Wow, danke. Ich habe eine Google-Suche durchgeführt, die normalerweise Stack Overflow-Ergebnisse anzeigt, aber ich bin völlig leer ausgegangen! – Darren