datedatetimetimeelixirtimex

Combine date and time to a datetime


How can I convert a Date and a Time to a DateTime?

Say I have the following date and time

iex> date = ~D[2018-01-01]
iex> time = ~T[00:00:01.000]

How can I combine these to output the datetime: #DateTime<2018-01-01 00:00:01Z> in a clean way?

The best I come up with is using the Timex library:

Timex.add(Timex.to_datetime(date), Timex.Duration.from_time(time))

but I feel that surely there is a nicer, more readable way to combine this.


Solution

  • If you are using the calendar library, you can use either the Calendar.DateTime.from_date_and_time_and_zone function or the Calendar.NaiveDateTime.from_date_and_time function:

    iex(4)> Calendar.DateTime.from_date_and_time_and_zone(~D[2018-10-01], ~T[12:22:22], "Australia/Melbourne")
    {:ok, #DateTime<2018-10-01 12:22:22+10:00 AEST Australia/Melbourne>}
    iex(5)> Calendar.NaiveDateTime.from_date_and_time(~D[2018-10-01], ~T[12:22:22])                           
    {:ok, ~N[2018-10-01 12:22:22]}
    

    There are also from_date_and_time! and from_date_and_time! variants.