I have the following function that Generateds a random date:
function createARandomDateBetweenRange(Carbon $start, Carbon $stop, int $weekDay=null) : Carbon
{
$randDate = random_int($start->getTimestamp(), $stop->getTimestamp());
$radomDate = Carbon::createFromTimestamp($randDate);
return $radomDate
}
But for some reason I need to be able to select a random Monday, tuesday etc etc from a provided weekday (0 is Sunday, 6 is Saturday)
So I changed the definition as:
use Carbon\Carbon;
public static function createARandomDateBetweenRange(Carbon $start, Carbon $stop, ?int $weekDay=null) : Carbon
{
$randDate = random_int($start->getTimestamp(), $stop->getTimestamp());
$radomDate = Carbon::createFromTimestamp($randDate);
if($weekDay!=null && $weeekDay >= Carbon::SUNDAY && $weekDay <= Carbon::SATURDAY)
{
// Modify the date in order to get the correct date here
}
return $radomDate;
}
So how I can get the correct date from a specified range of dated and that random datetime to be a specific weekday I provide as a parameter?
For example when I call the function like:
use Carbon\Carbon;
$now = Carbon::now()
$fiveMonthsLater= new Carbon($now);
$fiveMonthsLater->modify("+5 months");
$randomTuesday=createARandomDateBetweenRange($now,$fiveMonthsLater,Carbon::TUESDAY);
$randomSaturday=createARandomDateBetweenRange($now,$fiveMonthsLater,Carbon::SATURDAY);
echo $randomTuesday->isoFormat("dddd"); //Outputs Tuesday
echo $randomSaturday->isoFormat("dddd"); //Outputs Saturdat