-9

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)

Miquel Molina
  • 23
  • 2
  • 8
  • 1
    You need to use a [DateFormatter](https://developer.apple.com/documentation/foundation/dateformatter) to convert the Date into a string – Joakim Danielson Feb 08 '20 at 09:00

2 Answers2

0

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)
Kishan Bhatiya
  • 2,175
  • 8
  • 14
  • This will fail if the user sets his device time to 12h format – Leo Dabus Feb 08 '20 at 15:22
  • 1
    **if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ("en_US_POSIX" works the same on iOS as it does on OS X** – Leo Dabus Feb 08 '20 at 15:25
0
control.data.description

will give you some form of string representation but probably not what you wish for.

It will simply dump out all kinds of details in a comprehensive form that is not usually suitable for UI representation.

There's also

control.data.description(with: *some locale*)

but that's simply a localizad verion of the same. Maybe you want to have a look at DateFormatter.

The other way around is even harder, as it means parsing a string representation of a date.

In a very technological setting, you could use the ISO8601 standard for string representation of date and time. It's relatively common, has representations of date, time, date + time, optionally including time zones offsets, &c.

Plus, it is easy to parse.

In a more traditional / customer facing UI setting, you may want to opt for custom date controls in your GUI so you model can simply use a Date without conversion to and from strings, and the custom control takes care of displaying and editing date values.

yeoman
  • 1,671
  • 12
  • 15