A bit similar to this one, yet different.
I need to generate two random dates:
- First between
$startDate
and$endDate
- Second between generated first date and
$endDate
- Both with random hour falling between
$startHour
and$endHour
.
I am doing this like that:
$createDate = new DateTime();
$updateDate = new DateTime();
$createDate
->setTimestamp(rand($startDate, $endDate))
->setTime(rand($startHour, $endHour), rand(0, 59), rand(0, 59));
$updateDate
->setTimestamp(rand($createDate->getTimestamp(), $endDate))
->setTime(rand($startHour, $endHour), rand(0, 59), rand(0, 59));
How to modify the above code to assure that both createDate
and updateDate
does not fall on Sunday?
3
Answers
Try this:
Try add function, and no variables.
I modify your code to this:
Here, I used
do...while
loop to keep generating a random date until the generated date is not a Sunday. Theformat('N')
is used to returns the day of the week as an integer, and7
represents Sunday. The loop will continue untilformat('N')
does not return7
, ensuring that the generated date is not a Sunday*.*Note that this may be inefficient if the range of dates between
$startDate
and$endDate
includes many Sundays, as it may take several iterations to find a date that is not a Sunday. In such, you may want to consider generating a list of all weekdays within the date range and then randomly selecting from that list, as answered by @waterloomatt here.Additional
Add counter for a maximum number of attempts to prevent the loop from running indefinitely.
*The above may still has a possibility of infinite loop if the range of possible dates only includes Sundays and the maximum number of attempts is reached, so you could add additional logic to adjust the range of possible dates or handle the case where no non-Sunday dates are available.
The trouble with the other answers is that having your loop bounded by a random condition can put you in the situation where the loop sometimes takes an extremely long time to complete, or puts itself into a state where it can never complete.
A constant-time solution would be something like the below where we simply generate a list of valid dates, and then pick randomly from those according to the rules set.
Output:
Note that the upper/lower bounds for the create/update indexes are based on the assumption that neither can overlap with the start/end dates.
It should also be possible to approach the "no sundays" rule in a purely mathematical way based on the start/end and calculate the indices/offsets that way, but I’m just not feeling very math-y today.