1-- difference in seconds between two dates
2
3select extract(epoch from ('2020-03-30 09:55:56'::timestamp - '2020-03-30 08:54:55'::timestamp));
4-- result : 3661
1select age('2010-04-01', '2012-03-05'),
2 date_part('year',age('2010-04-01', '2012-03-05')),
3 date_part('month',age('2010-04-01', '2012-03-05')),
4 date_part('day',age('2010-04-01', '2012-03-05'));
1 -- Difference between Dec 30, 2011 08:54:55 and Dec 30, 2011 08:56:10 in minutes
2 SELECT (DATE_PART('day', '2011-12-30 08:56:10'::timestamp - '2011-12-30 08:54:55'::timestamp) * 24 * 60 +
3 DATE_PART('hour', '2011-12-30 08:56:10'::timestamp - '2011-12-30 08:54:55'::timestamp)) * 60 +
4 DATE_PART('minute', '2011-12-30 08:56:10'::timestamp - '2011-12-30 08:54:55'::timestamp);
5 -- Result: 1
6
7 -- Time only
8 SELECT DATE_PART('hour', '08:56:10'::time - '08:54:55'::time) * 60 +
9 DATE_PART('minute', '08:56:10'::time - '08:54:55'::time);
10 -- Result: 1
1 CREATE OR REPLACE FUNCTION DateDiff (units VARCHAR(30), start_t TIME, end_t TIME)
2 RETURNS INT AS $$
3 DECLARE
4 diff_interval INTERVAL;
5 diff INT = 0;
6 BEGIN
7 -- Minus operator for TIME returns interval 'HH:MI:SS'
8 diff_interval = end_t - start_t;
9
10 diff = DATE_PART('hour', diff_interval);
11
12 IF units IN ('hh', 'hour') THEN
13 RETURN diff;
14 END IF;
15
16 diff = diff * 60 + DATE_PART('minute', diff_interval);
17
18 IF units IN ('mi', 'n', 'minute') THEN
19 RETURN diff;
20 END IF;
21
22 diff = diff * 60 + DATE_PART('second', diff_interval);
23
24 RETURN diff;
25 END;
26 $$ LANGUAGE plpgsql;