Is there a way I can get a random date between two dates in Carbon? For example, I am trying to get a random date between now and 55 mins ago.
$dateNow = Carbon::now();
$date25MinsAgo = Carbon::now()->subMinutes(55);
However, I am stuck at this point. I found some info on php, but I want to use 'now' as it's a seeder. What should I do?
you want to generate random time between two given times, such as generate time from 6 o'clock to 9 o'clock, you can use below formula. Type this formula: =TEXT(RAND()*(8:45-7)/24+6/24,"HH:MM:SS") into a blank cell, and drag the fill handle over to the range that you want to insert the time.
Use rand()
:
$random = Carbon::now()->subMinutes(rand(1, 55));
Use random_int()
:
use Carbon\Carbon;
$upTo55MinsAgo = Carbon::now()->subMinutes(random_int(0, 55));
(PHP 7, PHP 8) random_int — Generates cryptographically secure pseudo-random integers
You can also use rand()
, but I think it's good practice to use the
cryptographically secure function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With