Search code examples
elixirecto

How can I get an Ecto.DateTime value representing the current time?


I want to get an Ecto.DateTime value that represents the current time.

How can I do that?


Solution

  • While DateTime.utc_now |> Ecto.DateTime.cast works, there is a simpler way with Ecto.DateTime.utc

    It's basically the same but with a different default precision:

    iex(30)> DateTime.utc_now |> Ecto.DateTime.cast
    {:ok, #Ecto.DateTime<2016-09-27 19:55:38.542000>}
    
    iex(31)> Ecto.DateTime.utc
    #Ecto.DateTime<2016-09-27 19:55:45>
    
    iex(32)> Ecto.DateTime.utc(:usec)
    #Ecto.DateTime<2016-09-27 19:55:48.162000>