Bobochka
11/29/2016 - 3:09 PM

PG DateDiff

PG DateDiff

DROP FUNCTION DateDiff (units VARCHAR(30), start_t TIMESTAMP, end_t TIMESTAMP );
CREATE OR REPLACE FUNCTION DateDiff(units VARCHAR(30), start_t TIMESTAMP, end_t TIMESTAMP)
  RETURNS FLOAT AS $$
DECLARE
  diff_interval INTERVAL;
  diff          INT = 0;
  years_diff    INT = 0;
  start_ts      TIMESTAMP(0) = start_t :: TIMESTAMP(0);
  end_ts        TIMESTAMP(0) = end_t :: TIMESTAMP(0);
BEGIN
  --   start_ts = start_t::TIMESTAMP(0)


  -- Minus operator returns interval 'DDD days HH:MI:SS'
  diff_interval = end_ts - start_ts;

  diff = diff + DATE_PART('day', diff_interval);

  diff = diff * 24 + DATE_PART('hour', diff_interval);
  diff = diff * 60 + DATE_PART('minute', diff_interval);
  diff = diff * 60 + DATE_PART('second', diff_interval);

  RETURN diff;
END;
$$ LANGUAGE plpgsql;