Search code examples
timeelixirectomilliseconds

Convert Ecto.DateTime to milliseconds


In Elixir, what is the best way to convert an Ecto.DateTime into integer milliseconds?

I saw this example and believe I have adapted it for milliseconds, but I want to know if there is any caveat to my approach.

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

Solution

  • The calculations looks correct to me. You improve this slightly using more pipes:

    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
    

    Output:

    1472105945416
    

    You may also want to replace that constant value with :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}), possibly storing it in a module attribute so that there's no performance hit, like how timex does.