時間をミリ秒単位で変換する方法Ecto.DateTime
に?タイムスタンプをElixirのDateTimeに変換するには?
ミリ秒単位の時間は、1970年1月1日00:00:00 UTCから経過したミリ秒数です。
時間をミリ秒単位で変換する方法Ecto.DateTime
に?タイムスタンプをElixirのDateTimeに変換するには?
ミリ秒単位の時間は、1970年1月1日00:00:00 UTCから経過したミリ秒数です。
は、ミリ秒の精度を維持しながら、これを行うための一つの方法です:
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 = 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
は、今では行うことは非常に簡単です:
timestamps |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!
は、より多くの詳細についてのDateTime
DateTime.from_unix(1466298513463, :millisecond)
にタイムスタンプを変換するにはhttps://hexdocs.pm/elixir/master/DateTime.html#from_unix/3