Combine date and time to a datetime

1.2k views Asked by At

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.

3

There are 3 answers

3
Penguin Brian On BEST ANSWER

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.

2
legoscia On

You can use NaiveDateTime.new/2:

iex> NaiveDateTime.new(date, time)
{:ok, ~N[2018-01-01 00:00:01.000]}

The reason it is a "naive datetime" instead of a datetime is that the Time struct doesn't contain time zone information. If you know the time zone, you can add that information using DateTime.from_naive/2:

iex> DateTime.from_naive(~N[2018-01-01 00:00:01.000], "Etc/UTC")
{:ok, #DateTime<2018-01-01 00:00:01.000Z>}
1
Aleksei Matiushkin On

While the answer by @legoscia is perfectly valid, here is how you deal with date and time pair (without Timex, just pure Elixir standard library):

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

{Date.to_erl(date), Time.to_erl(time)}
|> NaiveDateTime.from_erl!()
|> DateTime.from_naive("Etc/UTC")
#⇒ {:ok, #DateTime<2018-01-01 00:00:01Z>}