Add date to postgres by ecto

Hi All,
How could I insert to postgres date formatted like that -> “2020-01-14 12:00:00 UTC”

#migration
defmodule Hello.Repo.Migrations.Travels do
  use Ecto.Migration

  def change do
    create table(:travels, primary_key: false) do
      add(:arrived, :timezonetz, null: false, primary_key: true)
end


#travel.ex
defmodule Hello.Travel do
  use Ecto.Schema

   @primary_key false
   schema "travels" do
      field(:arrived, :utc_datetime, primary_key: true)
   end
end
> travel = %Hello.Travel{arrived: ~N[2020-01-16 10:35:00]}   
> Hello.Repo.insert(travel)

 (Ecto.ChangeError) value `~N[2020-01-16 10:35:00]` for `Hello.Travel.arrived` 
in `insert` does not match type :utc_datetime

the same is with

travel = %Hello.Travel{arrived: ~N[2018-12-30T16:00:00.000Z]}

ectos :utc_datetime primitive type only maps from a DateTime, your example though uses a NaiveDateTime.

Either use a DateTime as input, or use :naive_datetime in the DB.

Which solution is correct for you depends on the semantics of the value.

2 Likes

@NobbZ Thanks for response!
I’ve tried to change type in db by migrations but I failed ;/
How cound I invoke changes from migration file?
I rerun mix ecto.migrate but it returns Already up and nothing changed in db.

#migration
defmodule Hello.Repo.Migrations.Travels do
  use Ecto.Migration

  def change do
    create table(:travels, primary_key: false) do
      add(:arrived, :timezonetz, null: false, primary_key: true)
    end

    alter table(:travels) do
        modify(:arrived, :naive_datatime)
    end
  end
end

By workaround I drop tables travels, schema_migrations and rerun mix ecto.migrate

with :naive_database indeed works :slight_smile:, thanks!

You do not change migrations that already have run. You create a new migration that alters the database schema.

1 Like