By default “timestamps()” generates a timestamp in naive datetime. When and when not will it be better to use “utc_datetime” instead?
In my app I need to use the values of “timestamps()”. And in some point I need to compare the “now()” with :inserted_at and then call DateTime.diff(…) I believe that it’s better for me to use :utc_datetime in “timestamps()” , right?
this has been on this forum quite a few times already (search for utc_datetime). In short: when you use Ecto only, this should not matter as it enforces client’s protocol to be in UTC time zone. However, it makes difference if you load scripts or perform queries using
psql or other external tools, that can have different time zone settings.
No. I’m calling
DateTime.diff(DateTime.utc_now(), my_article.inserted_at) in my app and it throws an exception because the “inserted_at” is Naive DateTime
Ah, yes, this code will throw error unless you covert one type to another. I thought you meant SQL queries with “NOW()” function in them.
Hence, the answer to my question is – I should use :utc_datetime for “timestamps()”?
In my opinion - yes. That’s what I use and recommend to always use. (but opinions vary on this forum)
For as long as you’re not inserting the timestamps manually (e.g.
insert_all), but let ecto handle them you can basically switch them out at any time. Ecto does default to
NaiveDateTime.utc_now(), so it’s going to be a utc datetime no matter what and on the db side there’s no difference between an
How can I convert “inserted_at” from naive to utc so that I can use it in DateTime.diff(…) ?
DateTime.from_naive!(a.inserted_at, "Etc/UTC") or setup your schemas to use