How to generate random date between two dates using php?

89,435

Solution 1

PHP has the rand() function:

$int= rand(1262055681,1262055681);

It also has mt_rand(), which is generally purported to have better randomness in the results:

$int= mt_rand(1262055681,1262055681);

To turn a timestamp into a string, you can use date(), ie:

$string = date("Y-m-d H:i:s",$int);

Solution 2

If given dates are in date time format then use this easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.

A quick PHP example would be:

// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
    // Convert to timetamps
    $min = strtotime($start_date);
    $max = strtotime($end_date);

    // Generate random number using above bounds
    $val = rand($min, $max);

    // Convert back to desired date format
    return date('Y-m-d H:i:s', $val);
}

This function makes use of strtotime() as suggested by zombat to convert a datetime description into a Unix timestamp, and date() to make a valid date out of the random timestamp which has been generated.

Solution 3

Another solution using PHP DateTime

$start and $end are DateTime objects and we convert into Timestamp. Then we use mt_rand method to get a random Timestamp between them. Finally we recreate a DateTime object.

function randomDateInRange(DateTime $start, DateTime $end) {
    $randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
    $randomDate = new DateTime();
    $randomDate->setTimestamp($randomTimestamp);
    return $randomDate;
}

Solution 4

You can just use a random number to determine a random date. Get a random number between 0 and number of days between the dates. Then just add that number to the first date.

For example, to get a date a random numbers days between now and 30 days out.

echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));

Solution 5

Here's another example:

$datestart = strtotime('2009-12-10');//you can change it to your timestamp;
$dateend = strtotime('2009-12-31');//you can change it to your timestamp;

$daystep = 86400;

$datebetween = abs(($dateend - $datestart) / $daystep);

$randomday = rand(0, $datebetween);

echo "\$randomday: $randomday\n";

echo date("Y-m-d", $datestart + ($randomday * $daystep)) . "\n";
Share:
89,435
EzzDev
Author by

EzzDev

Updated on July 05, 2022

Comments

  • EzzDev
    EzzDev almost 2 years

    I am coding an application where i need to assign random date between two fixed timestamps

    how i can achieve this using php i've searched first but only found the answer for Java not php

    for example :

    $string = randomdate(1262055681,1262055681);