Show Time in 12 and 24 hour format in UIDatepicker on the basis of app settings not on device Settings

前端 未结 10 1101
夕颜
夕颜 2020-12-01 07:55

My problem is there is a switch in my app which toggles for 12 hour and 24 hour time format.I am displaying my labels time according to that, but the UIDatePicker

相关标签:
10条回答
  • 2020-12-01 08:13

    Swift 4 version of ak2g's answer:

    // myDatePicker is yourUIDatePicker Outlet
    @IBOutlet weak var myDatePicker: UIDatePicker!
    
    // For 24 Hrs 
    myDatePicker.locale = Locale(identifier: "en_GB")
    
    //For 12 Hrs
    myDatePicker.locale = Locale(identifier: "en_US")
    
    0 讨论(0)
  • 2020-12-01 08:13

    I've found an easier way, click on the UIDatePicker attributes inspector on storyboard, and set the locale to 'English (Europe)'. This takes away the AM/PM toggle and sets the time to 24hr format.

    0 讨论(0)
  • Just use, For 24 hours format:

    picker.locale = Locale.init(identifier: "en_gb")
    

    For 12 hours format:

    picker.locale = Locale.init(identifier: "en_us")
    

    Why this works? Because en_gb is for British English, which prefers 24 hr format. And you guessed it right, en_us is for American English which prefers 12 hr format.

    0 讨论(0)
  • 2020-12-01 08:17

    In Swift

        // myDatePicker is yourUIDatePicker Outlet
        @IBOutlet weak var myDatePicker: UIDatePicker!
    
        // For 24 Hrs 
        myDatePicker.locale = NSLocale(localeIdentifier: "en_GB") as Locale
    
        //For 12 Hrs
        timePickerView.locale = NSLocale(localeIdentifier: "en_US") as Locale
    
    0 讨论(0)
  • 2020-12-01 08:26

    Set your UIDatepicker to have a locale property so it doesn't default to the user's locale.

    Here is the documentation for doing so, and make sure to set the country, not the language.

    Edit: Actually, it looks like locale is depreciated in iOS 5.0. I guess Apple thought people shouldn't override it.

    0 讨论(0)
  • 2020-12-01 08:30

    For UIDatePicker you cannot change the time format to 24 or 12, it depends on the user local settings in setting.app

    0 讨论(0)
提交回复
热议问题