The PHP randomDate function will return a random date between two dates that are passed in. The format of the dates that you pass in are very relaxed so if you pass one date as July 1, 2019 and another date as 08/22/2019 it will return a date such as 2019-08-02 that is randomly between the two dates.

This function will parse about any English textual datetime representation because it uses the PHP strtotime function internally.

By default it returns the random date in a MySQL date format of Y-m-d such as 2019-07-10, but you can specify your own preferred format.

/**
 * Random Date
 *
 * This function will return a random date between two dates.
 *
 * Note: The format of the dates you provide usually do not matter, function will try and evalutate it.
 * Note: It does not matter if the first date specified is greater than or less than the second date, either works.
 *
 * @see https://www.php.net/manual/en/function.date.php for specifying the returning date format.
 *
 * @param string $firstDate A string representing the first date.
 * @param string $secondDate A string representing the second date.
 * @param string $format By default returns in Y-m-d, but you can use any format php date supports.
 * @return string Returns a random date between the two dates.
 */
function randomDate($firstDate, $secondDate, $format = 'Y-m-d'): string
{
    $firstDateTimeStamp = strtotime($firstDate);
    $secondDateTimeStamp = strtotime($secondDate);

    if ($firstDateTimeStamp < $secondDateTimeStamp) {
        return date($format, mt_rand($firstDateTimeStamp, $secondDateTimeStamp));
    }

    return date($format, mt_rand($secondDateTimeStamp, $firstDateTimeStamp));
}

This code snippet was published on It was last edited on

0

0 Comments

  • Votes
  • Oldest
  • Latest