swiftuikituidatepicker

How to get initial value of datePicker Swift


I want to get initial value of timePicker, value changes when I am just scrolling time. Please watch photos it will be more clear to understand what I want.

https://i.sstatic.net/hj5GA.jpg

@IBAction func datePickerChanged(_ sender: Any) {
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .short
    dateFormatter.dateFormat = "HH:mm"
    let strDate = dateFormatter.string(from: datePicker.date)
    datePickerLb.text = strDate
}

Solution

  • All you need is to update the label inside your viewDidLoad method. I would move the date formatter declaration out of that method to avoid creating a new one every time the value changes. Note that you should use timeStyle or dateFormat but not both. When displaying dates to the end user you should always respect the devices locale and settings so you should choose timeStyle in this case:


    let dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.timeStyle = .short
        return dateFormatter
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // your code
    
        // you can update the label here
        // datePickerLb.text = dateFormatter.string(from: datePicker.date)
        // or manually send the valueChanged action to force the update at view did load
        datePicker.sendActions(for: .valueChanged)
    }
    

    @IBAction func datePickerChanged(_ datePicker: UIDatePicker) {
        datePickerLb.text = dateFormatter.string(from: datePicker.date)
    }