Generate a Random Date Between Two Dates

As we learned in several earlier tips, we can create a random integer and a random string in YugabyteDB quite easily.

But what about a random date? We can that to, and one way would be to create a function like the following:

				
					CREATE OR REPLACE FUNCTION randomdate(DATE, DATE)
   RETURNS DATE AS
$$
DECLARE
   date1 DATE:=$1;
   date2 DATE:=$2;
BEGIN
  RETURN date1 + (floor(random() * ((date2 - date1) + 1))::INT);
END;
$$ language 'plpgsql';
				
			

Example:

				
					
yugabyte=# CREATE OR REPLACE FUNCTION randomdate(DATE, DATE)
yugabyte-#   RETURNS DATE AS
yugabyte-# $$
yugabyte$# DECLARE
yugabyte$#   date1 DATE:=$1;
yugabyte$#   date2 DATE:=$2;
yugabyte$# BEGIN
yugabyte$#   RETURN date1 + (floor(random() * ((date2 - date1) + 1))::INT);
yugabyte$# END;
yugabyte$# $$ language 'plpgsql';
CREATE FUNCTION

yugabyte=# SELECT randomdate('2022-01-01'::DATE, '2022-12-31'::DATE);
 randomdate
------------
 2021-02-16
(1 row)

yugabyte=# SELECT randomdate('2022-01-01'::DATE, '2022-12-31'::DATE);
 randomdate
------------
 2021-11-27
(1 row)
				
			

Have Fun!