【问题标题】:How to convert timestamp to DateTime in Elixir?如何在 Elixir 中将时间戳转换为 DateTime?
【发布时间】:2023-03-04 23:37:01
【问题描述】:

如何将时间以毫秒为单位转换为Ecto.DateTime

以毫秒为单位的时间是自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数。

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

    将时间戳转换为日期时间

    DateTime.from_unix(1466298513463, :millisecond)
    

    更多详情https://hexdocs.pm/elixir/master/DateTime.html#from_unix/3

    【讨论】:

      【解决方案2】:

      现在做起来很简单:

      timestamp |> DateTime.from_unix!(:millisecond) |> Ecto.DateTime.cast!
      

      【讨论】:

        【解决方案3】:

        这是一种在保持毫秒精度的同时做到这一点的方法:

        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
        

        演示:

        IO.inspect A.timestamp_to_datetime(1466329342388)
        

        输出:

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

        【讨论】:

          【解决方案4】:

          似乎可以通过以下方式完成,但是会丢失一些毫秒。

          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
          

          【讨论】:

            【解决方案5】:

            DateTime.from_unix 有单位作为第二个参数。 所以传入: :millisecond 或 :microsecond 关于你想要转换的值。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-11-08
              • 2020-10-09
              • 2019-12-24
              • 2011-12-18
              • 2019-11-30
              • 2021-01-04
              • 2021-01-12
              • 2020-09-11
              相关资源
              最近更新 更多