【发布时间】:2023-03-04 23:37:01
【问题描述】:
如何将时间以毫秒为单位转换为Ecto.DateTime?
以毫秒为单位的时间是自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数。
【问题讨论】:
如何将时间以毫秒为单位转换为Ecto.DateTime?
以毫秒为单位的时间是自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数。
【问题讨论】:
将时间戳转换为日期时间
DateTime.from_unix(1466298513463, :millisecond)
更多详情https://hexdocs.pm/elixir/master/DateTime.html#from_unix/3
【讨论】:
现在做起来很简单:
timestamp |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!
【讨论】:
这是一种在保持毫秒精度的同时做到这一点的方法:
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
【讨论】:
DateTime.from_unix 有单位作为第二个参数。 所以传入: :millisecond 或 :microsecond 关于你想要转换的值。
【讨论】: