SoFunction
Updated on 2025-04-08

Determine whether it is a number and date and time format function operation in postgresql database

During the process of writing GreenPlum function, I encountered a situation where I wanted to determine whether the string is in a number and date format. Based on the relationship between GreenPlum and postgresql, the following two functions were found.

--1. Determine whether a string is a number

CREATE OR REPLACE FUNCTION isnumeric(txtStr VARCHAR) RETURNS BOOLEAN
AS
$$
BEGIN
 
RETURN txtStr ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$';
 
END;
$$
LANGUAGE 'plpgsql';

--2. Determine whether the passed string is in date format

CREATE OR REPLACE FUNCTION isDate(dateStr VARCHAR) RETURNS BOOLEAN
AS
$$
BEGIN
 
IF (dateStr IS NULL) THEN 
   RETURN FALSE; 
END IF; 
   PERFORM dateStr::timestamp; 
   RETURN TRUE; 
EXCEPTION 
   WHEN others THEN 
   RETURN FALSE; 
 
END;
$$
LANGUAGE 'plpgsql';

Supplement: The conversion of timestamps and dates in Postgresql (also applicable to GreenPlum)

I won't say much nonsense, let's just read the code~

--Date to timestamp
SELECT EXTRACT(epoch FROM NOW()); 
SELECT EXTRACT(epoch FROM CAST('2017-12-06 00:17:10' AS TIMESTAMP)); 
 
--Timestamp to date
SELECT TO_TIMESTAMP(1512490630)

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.