How to generate random date between two dates using php ?

How to generate random date between two dates using php ?

Asked on December 28, 2018 in PHP.
Add Comment


  • 3 Answer(s)

    The  rand() function available in PHP ,

    $int= rand(1262055681,1262055681);
    

    The php also has a funtion called  mt_rand(),  that is pretend to have better  vacillation in the output.

    $int= mt_rand(1262055681,1262055681);
    

    We can use date() that is converte a timestamp into a string , Which means,

    $string = date("Y-m-d H:i:s",$int);
    
    Answered on December 28, 2018.
    Add Comment

    The random number can be used to determine a random date. Get the random number 0 to number of days in between the dates. After that add that number to the first date like here.

    Here is an example,

    echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));
    
    Answered on December 28, 2018.
    Add Comment

    Here is the different kind of approach,

    $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";
    
    Answered on December 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.