如何将毫秒为单位的时间转换为Ecto.DateTime
以毫秒为单位的时间是自1970年1月1日00:00:00 UTC以来经过的毫秒数。
发布于 2016-06-19 17:44:39
这里有一种方法可以在保持毫秒精度的同时做到这一点:
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
演示:
IO.inspect A.timestamp_to_datetime(1466329342388)
输出:
#Ecto.DateTime<2016-06-19 09:42:22.388000>
https://stackoverflow.com/questions/37905698
复制相似问题