How to convert timestamp to DateTime in Elixir?
Asked Answered
I

5

8

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.

Ignazio answered 19/6, 2016 at 9:19 Comment(0)
V
4

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>
Vereen answered 19/6, 2016 at 9:44 Comment(0)
E
19

To convert timestamps to DateTime

DateTime.from_unix(1466298513463, :millisecond)

For more Details https://hexdocs.pm/elixir/main/DateTime.html#from_unix/3

Effrontery answered 9/11, 2017 at 8:27 Comment(0)
O
15

Now it's very simple to do:

timestamp |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!
Outcome answered 13/2, 2017 at 3:4 Comment(0)
V
4

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>
Vereen answered 19/6, 2016 at 9:44 Comment(0)
I
0

Seems like it can be done the following way, but some milliseconds will be lost.

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
Ignazio answered 19/6, 2016 at 9:36 Comment(0)
U
0

DateTime.from_unix have unit as second argument. So passing in: :millisecond or :microsecond regarding to value you want to convert.

Unimpeachable answered 25/7, 2021 at 2:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.