I’m using laravel and carbon and want to generate random date and time between today and 30 days ago, something like 2023-08-28 13:50:14
if I use it like this
$randomDateTime = Carbon::now()->subDays(rand(0, 30));
I got the date randomized, but it will always got current time, is there a possibility to random the time also?
2
Answers
You can simply use
subSeconds()
to achieve this.I modified your code a bit while maintaining your 30 days requirement.
Add
startOfDay()
to get "00:00:00" andaddSeconds()
for random number between 23 hours, 59 minutes, and 59 seconds.