Getting random date and time between two dates using php carbon

112 Views Asked by At

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

There are 2 best solutions below

1
imlokesh On BEST ANSWER

You can simply use subSeconds() to achieve this.

$randomDateTime = Carbon::now()->subSeconds(rand(0, 30 * 24 * 60 * 60));
0
SirCoolMind On

I modified your code a bit while maintaining your 30 days requirement.

Add startOfDay() to get "00:00:00" and addSeconds() for random number between 23 hours, 59 minutes, and 59 seconds.

$randomDateTime = Carbon::now()->subDays(rand(0, 30))->startOfDay()-addSeconds(rand(0, 86399));