How to convert the time in milliseconds to Ecto.DateTime
?
The time in milliseconds is the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
How to convert the time in milliseconds to Ecto.DateTime
?
The time in milliseconds is the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
Here's one way to do this while preserving the millisecond accuracy:
defmodule A do
def timestamp_to_datetime(timestamp) do
epoch = :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})
datetime = :calendar.gregorian_seconds_to_datetime(epoch + div(timestamp, 1000))
usec = rem(timestamp, 1000) * 1000
%{Ecto.DateTime.from_erl(datetime) | usec: usec}
end
end
Demo:
IO.inspect A.timestamp_to_datetime(1466329342388)
Output:
#Ecto.DateTime<2016-06-19 09:42:22.388000>
To convert timestamps to DateTime
DateTime.from_unix(1466298513463, :millisecond)
For more Details https://hexdocs.pm/elixir/main/DateTime.html#from_unix/3
Now it's very simple to do:
timestamp |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!
Here's one way to do this while preserving the millisecond accuracy:
defmodule A do
def timestamp_to_datetime(timestamp) do
epoch = :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})
datetime = :calendar.gregorian_seconds_to_datetime(epoch + div(timestamp, 1000))
usec = rem(timestamp, 1000) * 1000
%{Ecto.DateTime.from_erl(datetime) | usec: usec}
end
end
Demo:
IO.inspect A.timestamp_to_datetime(1466329342388)
Output:
#Ecto.DateTime<2016-06-19 09:42:22.388000>
Seems like it can be done the following way, but some milliseconds will be lost.
timestamp = 1466298513463
base = :calendar.datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}})
seconds = base + div(timestamp, 1000)
erlang_datetime = :calendar.gregorian_seconds_to_datetime(seconds)
datetime = Ecto.DateTime.cast! erlang_datetime
DateTime.from_unix have unit as second argument. So passing in: :millisecond or :microsecond regarding to value you want to convert.
© 2022 - 2024 — McMap. All rights reserved.