Skip to content

Instantly share code, notes, and snippets.

@thiamteck
Created November 19, 2018 11:50
Show Gist options
  • Save thiamteck/dccb45d1dbc80619469a89fd6ec490a7 to your computer and use it in GitHub Desktop.
Save thiamteck/dccb45d1dbc80619469a89fd6ec490a7 to your computer and use it in GitHub Desktop.
MySQL function for get random datetime in between 2 given datetime. Copy from : https://stackoverflow.com/a/49727273
DELIMITER $$
DROP FUNCTION IF EXISTS `random_datetime_between`$$
CREATE FUNCTION `random_datetime_between`(date_from DATETIME, date_to DATETIME) RETURNS DATETIME
BEGIN
/**
* reference: https://stackoverflow.com/a/49727273
*/
DECLARE result DATETIME;
SET result = (SELECT FROM_UNIXTIME(
UNIX_TIMESTAMP(date_from) + FLOOR(
RAND() * (
UNIX_TIMESTAMP(date_to) - UNIX_TIMESTAMP(date_from) + 1
)
)
));
RETURN TIMESTAMP(result);
END$$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment