如何将毫秒为单位的时间转换为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>发布于 2017-02-13 11:04:13
现在做起来非常简单:
timestamp |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!发布于 2017-11-09 16:27:07
将时间戳转换为DateTime
DateTime.from_unix(1466298513463, :millisecond)有关更多详细信息,请访问https://hexdocs.pm/elixir/master/DateTime.html#from
https://stackoverflow.com/questions/37905698
复制相似问题