Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting random date between two dates

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?

like image 341
senty Avatar asked Jan 19 '17 08:01

senty


People also ask

How do I generate a random time between ranges in Excel?

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.


2 Answers

Use rand():

 $random = Carbon::now()->subMinutes(rand(1, 55));
like image 178
Alexey Mezenin Avatar answered Sep 24 '22 09:09

Alexey Mezenin


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.

like image 26
Daniel Dewhurst Avatar answered Sep 24 '22 09:09

Daniel Dewhurst