2012-08-31 134 views
5

我正在使用UIDatePicker来选择时间。我也在自定义选取器的背景,但是根据用户是否使用12小时模式(显示AM/PM列)或24小时模式,我需要2个不同的图像。 如何检测12/24小时的用户设置?检测iPhone 24小时时间设置

感谢

回答

3

,有可能是很多很多......

+0

哇,谢谢。我做了一个谷歌搜索,通常显示堆栈溢出结果,但我完全空白了! – Darren

31

甚至比别人更短:

NSString *format = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]]; 
BOOL is24Hour = ([format rangeOfString:@"a"].location == NSNotFound); 

说明

字符串格式化字符来表示的AM/PM符号是 “一”,如在Unicode Locale Markup Language – Part 4: Dates记录。

同样的文件也解释了特殊的模板符号“J”:

这是一种特殊用途的符号。它不能出现在模式或骨架数据中。相反,它被保留用于传递给API的骨架中,以便生成灵活的日期模式。在这种情况下,它根据语言环境的标准短时间格式是否使用h,H,K或k来确定语言环境(h,H,K或k)的首选小时格式。在实现这样的API时,在开始与availableFormats数据匹配之前,必须用h,H,K或k替换'j'。请注意,在传递给API的骨架中使用'j'是使骨架请求成为语言环境首选时间循环类型(12小时或24小时)的唯一方法。

NSString方法dateFormatFromTemplate:options:locale:在苹果的NSDateFormatter documentation描述:

返回表示适当地配置为指定的区域设置给定日期格式部件本地化日期格式字符串。

那么,什么方法做的就是打开你@"j"传递作为模板,以适合NSDateFormatter格式字符串。如果这个字符串在任何地方都包含am/pm符号@"a",那么您知道要显示am/pm的语言环境(以及由您为操作系统询问的其他用户设置)。

+0

我完全想投票你的答案,因为不工作,直到我读得更近。这很聪明。好一个! – Benjohn

+0

只是为了补充说明这不适用于模拟器。 – GuybrushThreepwood

4

斯威夫特(3.X)版本的日期延长的形式,两种最流行的解决方案:

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 
    }() 
} 

用法:

Date.is24HoursFormat_1 
Date.is24HoursFormat_2 

斯威夫特(2。0)版本的两个最流行的解决方案的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 
    }() 
} 

请注意,苹果称在NSDateFormatter(Date Formatters)以下:

创建的日期格式是不是一个便宜的操作。如果您很可能经常使用格式化程序 ,那么缓存 单个实例比创建和处理多个实例通常更高效。 一种方法是使用静态变量。

这就是静态的原因让

其次,你应该使用NSLocale.autoupdatingCurrentLocale()(用于is24HoursFormat_1),这样,你总是会得到实际的当前状态。