Skip to content

Instantly share code, notes, and snippets.

@johnpena
Created December 13, 2022 15:37
Show Gist options
  • Save johnpena/6127c0c475d64def3bf58182eef292db to your computer and use it in GitHub Desktop.
Save johnpena/6127c0c475d64def3bf58182eef292db to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION humanize_time_span(ts timestamp) RETURNS varchar AS
'
SELECT
CASE
WHEN (now() - ts::timestamp)::INT < 60 THEN 'Within the last minute'
WHEN ((now() - ts::timestamp)::INT) / 60 < 60 THEN ((now() - ts::TIMESTAMPTZ)::INT / 60)::INT || ' Minutes ago'
WHEN (now() - ts::TIMESTAMPTZ)::INT / (60 * 60) < 24 THEN ((now() - ts::TIMESTAMPTZ)::INT / (60 * 60))::INT || ' Hours ago'
ELSE ((now() - ts::TIMESTAMPTZ)::INT / (60 * 60 * 24))::INT || ' Days ago'
END
'
LANGUAGE SQL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment