想要DateTime
在Ecto模式和迁移中使用,而不是默认值NaiveDateTime
,也要timestamptz
在PostgreSQL中使用,而不是默认值timestamp
(aka。timestamp without time zone
)。
timestamptz
和:utc_datetime
注意:Ecto.Migration.timestamps / 1(源)全局配置始终可以在本地覆盖。
使用docs中的:migration_timestamps
配置选项:Ecto.Migration
# in ./config/dev.exs (for example) config :app, App.Repo, migration_timestamps: [type: :timestamptz]
并且可以Ecto.Migration.timestamps/1
像往常一样在迁移中使用:
# ./priv/repo/migrations/20190718195828_create_users.exs create table(:users) do add :username, :string, null: false timestamps() end
该 Postgres
适配器将自动切换灵药表示,以 DateTime
从
NaiveDateTime
。
使用Ecto.Migration.timestamps / 1的:type
选项:
defmodule App.Repo.Migrations.CreateUsers do use Ecto.Migration def change do create table(:users) do add :username, :string, null: false timestamps(type: :timestamptz) end end end
:utc_datetime
Ecto模式也需要进行修改以使用 :utc_datetime
,否则NaiveDateTime
默认情况下会期望它们
。稍微修改Ecto.Schema
docs中的示例
:
# Define a module to be used as base defmodule MyApp.Schema do defmacro __using__(_) do quote do use Ecto.Schema # In case one uses UUIDs @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id # ------------------------------------ @timestamps_opts [type: :utc_datetime] end end end # Now use MyApp.Schema to define new schemas defmodule MyApp.Comment do use MyApp.Schema schema "comments" do belongs_to :post, MyApp.Post timestamps() end end
defmodule ANV.Accounts.User do use Ecto.Schema # -- EITHER -------------------------- @timestamps_opts [type: :utc_datetime] schema "users" do field :username, :string # -- OR ----------------------- timestamps(type: :utc_datetime) end
Ecto中的:utc_datetime和:naive_datetime之间的差异
劳/ tzdata
DateTime
在Elixir中,“ 只能处理“ Etc / UTC”日期时间 ”,但可以使用自定义的时区数据库进行配置,这就是该 tzdata
库
PostgreSQL,Elixir和Phoenix中的时区以及 如何在Ecto中将时间戳设置为UTC日期时间
第一篇文章中的一个非常方便的表格:
+----------------------+------------------+------------------------+------------------------------+-----------------------------------+ | Ecto 3 type | Elixir type | Supports microseconds? | Supports DateTime functions? | Supports NaiveDateTime functions? | +----------------------+------------------+------------------------+------------------------------+-----------------------------------+ | :utc_datetime_usec | DateTime | YES | YES | YES | | :utc_datetime | DateTime | NO | YES | YES | | :naive_datetime_usec | NaiveDateTime | YES | NO | YES | | :naive_datetime | NaiveDateTime | NO | NO | YES | +----------------------+------------------+------------------------+------------------------------+-----------------------------------+
特定于PostgreSQL的讨论和建议
不要使用时间戳(无时区)(PostgreSQL Wiki)
PostgreSQL中带/不带时区的时间戳之间的差异
在Rails和PostgreSQL中完全忽略时区(可接受的答案)
8.5。日期/时间类型(PostgreSQL手册)
9.9.3。时区(PostgreSQL手册)