I\'m using a UIDatePicker to select a time. I am also customising the background of the picker, however I need 2 different images depending on whether the user is using 12 hour
Swift (3.x) version of two most popular solutions in form of Date extension :
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
}()
}
Usage :
Date.is24HoursFormat_1
Date.is24HoursFormat_2
Swift (2.0) version of two most popular solutions in form of NSDate extension :
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
}()
}
Please note that Apple says following on NSDateFormatter (Date Formatters) :
Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.
Thats the reason for static let
Secondly you should use NSLocale.autoupdatingCurrentLocale() ( for is24HoursFormat_1 ), that way you will always get the actual current state.