Search code examples
elixirecto

How to convert timestamp to DateTime in Elixir?


How to convert the time in milliseconds to Ecto.DateTime?

The time in milliseconds is the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.


Solution

  • Here's one way to do this while preserving the millisecond accuracy:

    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
    

    Demo:

    IO.inspect A.timestamp_to_datetime(1466329342388)
    

    Output:

    #Ecto.DateTime<2016-06-19 09:42:22.388000>