How to accept date and datetime into the same field

Hey I would need to save these 2 types of dates into one field

"start_date": "2019-10-18",
"start_date": "2019-10-18T20:00:00+02"

as you can see one is a date and the other is a datetime.
what’s the best way to go about this?
maybe convert them into something else?
and then transform them back when i want to return them?

this doesn’t sound so good… maybe store them in seperate fields?

If You need to keep time info, then convert Date to DateTime, if You don’t, convert DateTime to Date. Anyway, it’s not good practice to do

2 types of dates into one field

As others said, it is likely a bad idea, but assuming you have to handle such input for reasons beyond your control, you can always trying parsing as one and then fallback to the other. I am not sure which order is best but here is an example:

case Date.from_iso8601(maybe_datetime) do
  {:ok, date} -> convert_date_to_datetime(...)
  {:error, _} ->
    case NaiveDateTime.from_iso(maybe_datetime) do
      {:ok, naive} -> convert_naive_to_datetime(...)
      {:error, _} -> ...
    end
end
3 Likes

yes, i am trying to push back on this, but not my call at the end of the day, thanks for the suggestion!