by Ahmed90 · 7y ago · 0 comments
Use timestamp with tz, drop Unix timestamps and use ISO8601 DateTime format across the application ezpz never look back
When you store something as timestamptz, postgres converts it to UTC and "loses" the timezone part.
The only difference between timestamptz and timestamp is that when postgres is returning the timestamptz to you, it converts it back to your local time zone defined by SET TIME ZONE (and not the time zone it was originally stored in)
So basically if you store a timestamptz, you cannot convert it back to the local time, as the local time is never even stored.
I personally had to add a second `timezone` column to my table to store the timezone of the date.
E.g., when you do store the timezone separately, use `timestamp without time zone`: `time AT TIME ZONE timezone` [1] only does the right thing (i.e., interpreting `time` as relative to `timezone`, and producing an absolute time corresponding to it) if `time` is `without time zone`. (If `time` is `with time zone`, it produces the local time corresponding to the absolute time `time`, which is mathematically exactly the opposite of what you want.)
[1] https://www.postgresql.org/docs/current/functions-datetime.h...
Unfortunately the poor naming is a big faux pas.
I really really expected timestamp with time zone to store the time zone.
https://www.postgresql.org/docs/9.1/datatype-datetime.html
"For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's timezone parameter, and is converted to UTC using the offset for the timezone zone."
'timestamp with timezone' is kind of a gotcha. i guess it combines two things into one type that are logically one type but it also might mislead someone into believing the type is something else.
For calendaring or other applications where time zone’s shifting offsets can cause issues you need to store the UTC time along with the timezone and then do the conversion on read.