Getting random date and time between two dates using php carbon

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?

>Solution :

You can simply use subSeconds() to achieve this.

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

Leave a Reply