Fuse separate date and time into one datetime object?

I’m trying to take two separate HTML date and time objects and fuse them into one NaiveDateTime object. The date is HTML date format (“YYYY-MM-DD”); the time is HTML time format (“HH:mm:ss”). I have been trying functions in Timex, but none seem to quite achieve what it is I’m attempting to do.

If dates are always in iso8601 format you can use Date.from_iso8601 and Time.from_iso8601 to parse the date and time and you can use NaiveDateTime.new(date, time) to put them together. If your dates are in different formats you’d need to look at e.g. timex, which has broader parsing capabilities then elixir itself.

3 Likes

You can always just slam them together with a T inbetween, then parse that:

iex> dates = "2019-02-03"
"2019-02-03"
iex> times = "12:13:14"
"12:13:14"
iex> NaiveDateTime.from_iso8601("#{dates}T#{times}")
{:ok, ~N[2019-02-03 12:13:14]}

# Can do it via Timex too, like if you have a different format or something
iex> Timex.parse("#{dates}T#{times}", "{ISO:Extended}")
{:ok, ~N[2019-02-03 12:13:14]}
3 Likes

Thank you so very much. I swore it wouldn’t be this easy at all, but I guess I haven’t been playing with Timex enough.

1 Like