IPhone 24-hour time detection

I use UIDatePicker for timing. I also adjust the background of the collector, however I need two different images depending on whether the user uses 12-hour mode (which displays the AM / PM table) or 24-hour mode. How can I determine user settings within 12/24 hours?

thank

+5
source share
3 answers

and there are probably many, many more ...

+3
source

Even shorter than the rest:

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

Explanation

The string formatting character for representing the am / pm character is "a", as described in Unicode Markup Language - Part 4: Dates .

"j" :

. . , API-, . (h, H, K k), h, H, K, k . API "j" h, H, K k . , "j" , API, (12- 24-).

NSString dateFormatFromTemplate:options:locale: Apple NSDateFormatter:

, , .

, , @"j", , NSDateFormatter. am/pm @"a" , , ( , ), am/pm.

+31

Swift (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

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

, Apple NSDateFormatter ( ):

. , , , , . .

let

-, NSLocale.autoupdatingCurrentLocale() ( is24HoursFormat_1), .

+4

All Articles