Swift (3.x) wersja z dwóch najbardziej popularnych rozwiązań w postaci Data rozszerzenia:
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
}()
}
Zastosowanie:
Date.is24HoursFormat_1
Date.is24HoursFormat_2
Swift (2.0) Wersja z dwóch najbardziej popularnych rozwiązań w postaci przedłużenia NSDate:
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
}()
}
Należy pamiętać, że Apple mówi po dniu NSDateFormatter (Date Formatters):
Tworzenie datę formatowania nie jest tania eksploatacja. Jeśli prawdopodobnie używasz często formatera, zwykle wydajniej jest buforować pojedynczą instancję niż tworzyć i usuwać wiele instancji. Jednym ze sposobów jest użycie zmiennej statycznej.
Ów powód dla statycznych niech
drugie należy użyć NSLocale.autoupdatingCurrentLocale() (dla is24HoursFormat_1), w ten sposób zawsze będziesz uzyskać rzeczywisty stan obecny.
Wow, dzięki. Zrobiłem wyszukiwarkę Google, która zwykle pokazuje wyniki przepełnienia stosu, ale pojawił się zupełnie pusty! – Darren