Reputation: 333
I currently have a Date
and a Time
that I would really like to combine into a DateTime
struct.
Prior to Ecto 3 you could do this with Ecto.DateTime.from_date_and_time
but in the new documentation since the Ecto Types were deprecated I can't find an equivalent function.
The function currently looks like:
def add_datetime(date_as_string) do
(_, date = Date.from_iso8601(date)
end_time = #T[23:59:59]
datetime = datetime_add(Ecto.DateTime.from_date_and_time(date, end_time), -3, "day")
end
One of the constraints of this particular project is that I would like to avoid adding a third party library like Timex if at all possible but I am lost after looking at the current Elixir documentation.
Upvotes: 1
Views: 504
Reputation: 23091
With DateTime.new/4
:
iex(1)> DateTime.new(~D[2022-11-19], ~T[21:49:00])
{:ok, ~U[2022-11-19 21:49:00Z]}
You can also specify the time zone, if you set up a time zone database:
iex(2)> Mix.install [:tz]
iex(3)> Calendar.put_time_zone_database(Tz.TimeZoneDatabase)
iex(4)> DateTime.new(~D[2022-11-19], ~T[21:49:00], "Asia/Tokyo")
{:ok, #DateTime<2022-11-19 21:49:00+09:00 JST Asia/Tokyo>}
Upvotes: 0
Reputation: 333
For anyone finding this on Google you can also use a NaiveDateTime
if you don't care about the timezone information:
datetime= NaiveDateTime.new(date_struct, time_struct)
|> DateTime.from_naive("Etc/UTC")
Upvotes: 0
Reputation: 1629
You can use DateTime.from_iso8601/2
.
datetime_iso8601 = "#{Date.to_iso8601(date)}T#{Time.to_iso8601(time)}+03:30"
{:ok, datetime, offset_from_utc} = DateTime.from_iso8601(datetime_iso8601)
Instead of +3:30
use your desired offset, or Z
for UTC.
Upvotes: 2