Search code examples
swiftdatecell

how to convert string to date or date to string


I have a tableview cell with a Date type Date, it shows me the following error and I don't know how to fix it:

Error: Cannot assign value of type 'Date' to type 'String?'

cell.Resum_Controls_Data_txt.text = control.data

control.data (is type Date)


Solution

  • Resum_Controls_Data_txt is type of String not Date, so you have to convert date to string using DateFormatter as follow:

    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "HH:mm E, d MMM y" //add date format whichever you want
    cell.Resum_Controls_Data_txt.text = formatter.string(from: control.data)