将 Ecto.DateTime 转换为毫秒

Convert Ecto.DateTime to milliseconds

在 Elixir 中,将 Ecto.DateTime 转换为整数毫秒的最佳方法是什么?

我看到 this example 并且相信我已经适应了它几毫秒,但我想知道我的方法是否有任何警告。

(((datetime
   |> Ecto.DateTime.to_erl
   |> :calendar.datetime_to_gregorian_seconds
   |> Kernel.-(62167219200)) * 1000000) + datetime.usec)
|> div(1000)

我认为这些计算是正确的。您可以使用更多管道稍微改进一下:

datetime = Ecto.DateTime.utc(:usec)

datetime
|> Ecto.DateTime.to_erl
|> :calendar.datetime_to_gregorian_seconds
|> Kernel.-(62167219200)
|> Kernel.*(1000000)
|> Kernel.+(datetime.usec)
|> div(1000)
|> IO.inspect

输出:

1472105945416

您可能还想用 :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}) 替换该常量值,可能将其存储在模块属性中,这样就不会影响性能,例如 timex does.