Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TIMESTAMP vs TIMESTAMPTZ correct value when taking time difference

For the query:

SELECT '2018-03-01'::TIMESTAMP - '2018-09-01'::TIMESTAMP, 
       '2018-03-01'::TIMESTAMPTZ - '2018-09-01'::TIMESTAMPTZ;

the values -184 days for TIMESTAMP and -183 days -23:00:00 for TIMESTAMPTZ is returned.

To me, -184 days "seems" correct but I was always told to use TIMESTAMPTZ. Which is the correct answer?

like image 506
Liondancer Avatar asked May 23 '18 21:05

Liondancer


Video Answer


1 Answers

Answer posted as complement to comment discussion under OP's question.


Data type timestamptz is actually timestamp with time zone, while timestamp is timestamp without time zone.

The result that you get from substracting these specific dates like below is correct with 1 hour difference

SELECT '2018-03-01'::TIMESTAMPTZ - '2018-09-01'::TIMESTAMPTZ;

this is because 2018-03-01::timestamptz has +01 whereas 2018-09-01 has +02.

See it for yourself with this query

SELECT '2018-03-01'::TIMESTAMPTZ, '2018-09-01'::TIMESTAMPTZ

1 hour difference most likely comes from daylight savings and changing timezone over time.


In general I would always choose to include time zones within my system to properly handle time differences across the world and avoid issues that may arise from not having this. Client and server may have different timezones which can lead to problems.

like image 193
Kamil Gosciminski Avatar answered Oct 16 '22 12:10

Kamil Gosciminski