Pavan Kumar
Pavan Kumar

Reputation: 1881

Ecto date field striping of timezone info

I have date variable with timezone info. When I insert it into to DB using ecto, it strips off the time zone value and saves. Shouldn’t it instead convert it to UTC before saving to DB? If that’s not default behaviour is there a way to configure it?

date = Timex.now("Asia/Kolkata")
user = %User{
    name: "Bob",
    last_login: date,
}
Repo.insert(user)

# user got saved with last_login field with date - striped off timezone info.
# While inserted_at and updated_at always saves the DateTime in UTC.

Upvotes: 0

Views: 204

Answers (1)

Pavan Kumar
Pavan Kumar

Reputation: 1881

If the last_login field has data type of :naive_datetime the timezone info will be stripped off without converting time to UTC. Please use :utc_datetime instead

Example:

Replace following

defmodule SomeModule.Profile do
  use Ecto.Schema

  schema "profiles" do
    field :login_time, :naive_datetime
    # ...
    timestamps()
  end

end

With

defmodule SomeModule.Profile do
  use Ecto.Schema

  schema "profiles" do
    field :login_time, :utc_datetime
    # ...
    timestamps()
  end

end

Upvotes: 1

Related Questions