如何在 Elixir 中将时间戳转换为 DateTime?

How to convert timestamp to DateTime in Elixir?

如何将以毫秒为单位的时间转换为Ecto.DateTime

以毫秒为单位的时间是自 1970 年 1 月 1 日以来经过的毫秒数 00:00:00 UTC。

好像可以通过下面的方式完成,但是会损失一些毫秒。

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

这是在保持毫秒精度的同时执行此操作的一种方法:

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>

现在做起来很简单:

timestamp |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!

将时间戳转换为 DateTime

DateTime.from_unix(1466298513463, :millisecond)

更多详情https://hexdocs.pm/elixir/master/DateTime.html#from_unix/3

DateTime.from_unix 将单位作为第二个参数。 因此传入: :millisecond 或 :microsecond 关于您要转换的值。