In this article, we will see how to generate a random date between two dates using PHP.

To generate a random date between two dates, we have to use the built-in PHP functions strtotime(), rand(), and date().

To convert the input date strings to Unix timestamps, we use the strtotime() function. Unix timestamps are the number of seconds elapsed since January 1, 1970.

To generate a random integer between the given minimum & maximum timestamps we use the rand() function.

To convert the random Unix timestamp to human-readable date string we use the date().First argument of the date() function contains the desired output format.

In the following example, we use the “Y-m-d” format.

Following is the example program on how to generate a random date between two dates.

<?php

function randomDate($startDate, $endDate) {
    $minTimestamp = strtotime($startDate);
    $maxTimestamp = strtotime($endDate);
    $randomTimestamp = rand($minTimestamp, $maxTimestamp);
    $randomDate = date('Y-m-d', $randomTimestamp);
    return $randomDate;
}

$startDate = '2020-01-01';
$endDate = '2020-12-31';

$randomDate = randomDate($startDate, $endDate);
echo "Random date between $startDate and $endDate: $randomDate";

?>

Categorized in:

Tagged in: