Skip to content

Instantly share code, notes, and snippets.

@samcrosoft
Created September 13, 2013 13:09
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samcrosoft/6550473 to your computer and use it in GitHub Desktop.
Save samcrosoft/6550473 to your computer and use it in GitHub Desktop.
A PHP Method to generate random dates between two dates specificed with a format
<?php
/**
* 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);
}
@siekanski
Copy link

very helpfull method :)

@ManojKiranA
Copy link

thanks a lot i will add this to my laravel pacakage sir and credit will be added https://github.com/ManojKiranA/laravelhelpers

@ManojKiranA
Copy link

i have updated your function to my requirement

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

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

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

@Zarky2k2
Copy link

thanks <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment