Skip to content

Instantly share code, notes, and snippets.

@phpfiddle
Created October 16, 2017 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpfiddle/b0816acab8d7ca36767b9ad08102426d to your computer and use it in GitHub Desktop.
Save phpfiddle/b0816acab8d7ca36767b9ad08102426d to your computer and use it in GitHub Desktop.
[ Posted by Hasan ] function to generate random date between two initial dates
<?php
// function to generate random date between two dates with optional parameters
function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
switch ($mode) {
case "debug":
$rndDate = $startDate;
break;
case "epoch":
$rndDate = rand($startDate + date("Z"), $endDate + date("Z"));
break;
case "vepoch":
$rndDate = mt_rand($startDate + date("Z"), $endDate + date("Z"));
break;
case "verbose":
$rndDate = mt_rand($startDate, $endDate);
break;
default:
$rndDate = rand($startDate, $endDate);
break;
}
switch (is_numeric($timezone)) {
case true:
$timezone = $timezone * 60 * 60;
$result = gmdate($format, $rndDate + $timezone);
break;
case false:
date_default_timezone_set($timezone);
$result = gmdate($format, $rndDate);
break;
default:
date_default_timezone_set("UTC");
$result = gmdate($format, $rndDate);
break;
}
return $result;
}
echo "Test Dates: 1942-01-19 , 2016-06-03 <br>";
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
echo 'GMT -4 offset random verbose epoch: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", -4, "vepoch") . '<br>';
echo 'GMT -4 offset random epoch: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", -4, "epoch") . '<br>';
echo 'GMT -4 offset random verbose: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", -4, "verbose") . '<br>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment