Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 334
Jochen Österreicher Avatar asked Nov 28 '22 22:11

Jochen Österreicher


1 Answers

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.

like image 130
rmaddy Avatar answered Dec 18 '22 16:12

rmaddy