Setting ecto timestamps to utc_datetime globally

I was looking around in the ecto documentation and I could not find if is there a way to config ecto to use utc_datetime instead naive_datetime. I know that there is the option of setting the specific migration and schema, however I want this to be at project level.

Does anyone know if this is possible?

Check the migration_timestamps option here:

https://hexdocs.pm/ecto_sql/Ecto.Migration.html#module-migrations-configuration

Basically:

config :my_app, MyApp.Repo,
  migration_timestamps: [type: :utc_datetime_usec],
  database: "myapp_dev",
  username: "postgres",
  password: "postgres",
  hostname: "localhost"

As an extra, you can just make a module with a __using__ macro so you can just inject such options per Ecto.Schema if needed.

3 Likes

just adding that you might want to change the timestamps on the schema, that is a different thing from the migration timestamps:
https://hexdocs.pm/ecto/Ecto.Schema.html#module-schema-attributes

I usually have my own Schema module that when I use it, it sets the schema attributes to avoid forgetting it on the actual schema modules… something like

defmodule MyApp.Schema do
  def __using__(_opts) do
    quote do
      use Ecto.Schema
      @primary_key {:id, :binary_id, autogenerate: true}
      @foreign_key :binary_id
      @timestamp_opts [type: :naive_datetime]
    end
  end
end
3 Likes

Yes, I do the same. It complements the migration timestamps option.