Search code examples
iosswiftdatedatepickernsdateformatter

Swift 3 changing date format


I want to get my Date in DD.MM.YYYY HH:mm:ss as a String.

I use the following extension:

extension Date {
var localTime: String {
    return description(with: Locale.current)
    }
}

and the following code when my datePicker changes:

@IBAction func datePickerChanged(_ sender: UIDatePicker) {
    dateLabel.text = datePicker.date.localTime
    let formatter = DateFormatter()
    formatter.dateFormat = "dd.MM.yyyy hh:mm"
    let TestDateTime = formatter.date(from: datePicker.date.localTime)
}

What am I doing wrong?


Solution

  • Your code is completely wrong. Just do the following:

    @IBAction func datePickerChanged(_ sender: UIDatePicker) {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd.MM.yyyy HH:mm"
    
        dateLabel.text = formatter.string(from: sender.date)
    }
    

    This will convert the date picker's chosen date to a string in the format dd.MM.yyyy HH:mm in local time.

    Never use the description method to convert any object to a user presented value.