How to generate random date between two dates using php?

Viewed 95439

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);
15 Answers

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);

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.

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'));

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";

An other solution where we can use date_format :

 /**
 * Method to generate random date between two dates
 * @param $sStartDate
 * @param $sEndDate
 * @param string $sFormat
 * @return bool|string
 */

function randomDate($sStartDate, $sEndDate, $sFormat = 'Y-m-d H:i:s') {
    // Convert the supplied date to timestamp
    $fMin = strtotime($sStartDate);
    $fMax = strtotime($sEndDate);
    // Generate a random number from the start and end dates
    $fVal = mt_rand($fMin, $fMax);
    // Convert back to the specified date format
    return date($sFormat, $fVal);
}

Source : https://gist.github.com/samcrosoft/6550473

You could use for example :

$date_random = randomDate('2018-07-09 00:00:00','2018-08-27 00:00:00');

i had a same situation before and none of the above answers fix my problem so i

Came with new function

function randomDate($startDate, $endDate, $count = 1 ,$dateFormat = 'Y-m-d H:i:s')
{
   //inspired by
    // https://gist.github.com/samcrosoft/6550473

    // Convert the supplied date to timestamp
    $minDateString = strtotime($startDate);
    $maxDateString = strtotime($endDate);

    if ($minDateString > $maxDateString) 
    {
        throw new Exception("From Date must be lesser than to date", 1);

    }

    for ($ctrlVarb = 1; $ctrlVarb <= $count; $ctrlVarb++) 
    { 
       $randomDate[] = mt_rand($minDateString, $maxDateString); 
    }
    if (sizeof($randomDate) == 1) 
    {
        $randomDate = date($dateFormat, $randomDate[0]);
        return $randomDate;
    }elseif (sizeof($randomDate) > 1) 
    {
        foreach ($randomDate as $randomDateKey => $randomDateValue) 
        {
           $randomDatearray[] =  date($dateFormat, $randomDateValue);
        }
        //return $randomDatearray;
        return array_values(array_unique($randomDatearray));
    }
}

Now the testing Part(Data may change while testing )

$fromDate = '2012-04-02';
$toDate = '2018-07-02';

print_r(randomDate($fromDate,$toDate,1));

result will be

2016-01-25 11:43:22

print_r(randomDate($fromDate,$toDate,1));

array:10 [▼
  0 => "2015-08-24 18:38:26"
  1 => "2018-01-13 21:12:59"
  2 => "2018-06-22 00:18:40"
  3 => "2016-09-14 02:38:04"
  4 => "2016-03-29 17:51:30"
  5 => "2018-03-30 07:28:48"
  6 => "2018-06-13 17:57:47"
  7 => "2017-09-24 16:00:40"
  8 => "2016-12-29 17:32:33"
  9 => "2013-09-05 02:56:14"
]

But after the few tests i was thinking about what if the inputs be like

$fromDate ='2018-07-02 09:20:39';
$toDate = '2018-07-02 10:20:39';

So the duplicates may occur while generating the large number of dates such as 10,000

so i have added array_unique and this will return only the non duplicates

if you use laravel then it's for you.

\Carbon\Carbon::now()->subDays(rand(0, 90))->format('Y-m-d');

Pretty good question; needed to generate some random sample data for an app.

You could use the following function with optional arguments to generate random dates:

function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
    return $result;
}

sample input:

echo 'UTC: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", "utc") . '<br>';
//1942-Jan-19 07:00:00

echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '<br>'; 
//1942/Jan/19 00:00 AM

echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '<br>';
//1942 January

echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '<br>';
//20:00:00

echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '<br>';
//1942-Jan-19 02:00:00

echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '<br>';
//1942-Jan-19 00:00:00

readers requirements could vary from app to another, in general hope this function is a handy tool where you need to generate some random dates/ sample data for your application.

Please note that the function initially in debug mode, so change it to $mood="" other than debug in production .

The function accepts:

  1. start date
  2. end date
  3. format: any php accepted format for date or time
  4. timezone: name or offset number
  5. mode: debug, epoch, verbose epoch or verbose

the output in not debug mode is random number according to optional specifications.

tested with PHP 7.x

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

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

    // Convert back to date
    return Carbon::createFromTimestamp($val);
}

dd($this->randomDate('2014-12-10', Carbon::now()->toString()));

Using carbon

Related