Cannot set 24 h format on UIDatePicker in iOS14

Viewed 1455

I can't set UIDatePicker to be in 24 hours format, when the style is set to .compact.

I can set the format to 24 hours when the Date Picker's style is set to .wheels or .inline.

As seen in the code below, I set the locale on my Date Formatter to "en_GB" to get 24h format. The simulator is set to United States as region when reproducing this.

If I don't set the locale, then the .compact style also presents the AM/PM selectors, which is not present when using the code below.

This is my code, the UIDatePicker is added as the only item in the Storyboard:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!

    var dateFormatter = DateFormatter()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // setting this should give 24 hr format also in United States region, but it doesn't 
        dateFormatter.locale = Locale(identifier: "en_GB") 
    
        datePicker.locale = dateFormatter.locale
        datePicker.datePickerMode = .time
        datePicker.preferredDatePickerStyle = UIDatePickerStyle.compact
    }
}

Am I missing something here, or can't it be done for the .compact style?

2 Answers

There is no way that you can change the format of your UIDatePicker in your app. The format of the Date Picker is the same format that the user selected in the Settings app. Simply go to Settings -> General -> Date and Time to change the format on your device.

I experimented with this in iOS 14 Simulator. It appears the ordering of assigning properties matters.

This works:

let datePicker = UIDatePicker()
datePicker.locale = NSLocale(localeIdentifier: "en_GB") as Locale // 24 hour time
datePicker.timeZone = TimeZone(identifier: "UTC")
datePicker.datePickerMode = .dateAndTime
datePicker.preferredDatePickerStyle = .inline

This does not work:

let datePicker = UIDatePicker()
datePicker.timeZone = TimeZone(identifier: "UTC")
datePicker.datePickerMode = .dateAndTime
datePicker.preferredDatePickerStyle = .inline
datePicker.locale = NSLocale(localeIdentifier: "en_GB") as Locale // 24 hour time

Placing the Locale setting last appears to not work and exposes a bug in UIKit where the am/pm setting is not exposed, leading to only hours 01-12 setting possible.

Related