2016-08-24 114 views
1

在Elixir中,將Ecto.DateTime轉換爲整數毫秒的最佳方法是什麼?將Ecto.DateTime轉換爲毫秒

我看到了this example,我相信我已經適應了它幾毫秒,但我想知道是否有任何告誡我的方法。

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

回答

1

這個計算看起來對我來說是正確的。您改善這種略帶使用更多的管道:

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