dar*_*123 10
现在这很简单:
timestamp |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!
Run Code Online (Sandbox Code Playgroud)
小智 7
将时间戳转换为DateTime
DateTime.from_unix(1466298513463, :millisecond)
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息https://hexdocs.pm/elixir/master/DateTime.html#from_unix/3
这是在保持毫秒精度的同时做到这一点的一种方法:
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
Run Code Online (Sandbox Code Playgroud)
演示:
IO.inspect A.timestamp_to_datetime(1466329342388)
Run Code Online (Sandbox Code Playgroud)
输出:
#Ecto.DateTime<2016-06-19 09:42:22.388000>
Run Code Online (Sandbox Code Playgroud)