Getting random date between two dates
Asked Answered
P

3

16

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?

Pneumectomy answered 19/1, 2017 at 8:49 Comment(3)
Already answered hereLeitmotiv
Possible duplicate of How to generate random date between two dates using php?Larsen
@Leitmotiv that uses date() not carbon.Lakeishalakeland
T
40

Use rand():

 $random = Carbon::now()->subMinutes(rand(1, 55));
Therontheropod answered 19/1, 2017 at 8:51 Comment(0)
M
12

To get a random date in the last year:

$random = Carbon::today()->subDays(rand(0, 365));
Micaelamicah answered 24/12, 2020 at 9:51 Comment(1)
Nice, I'm using $random = Carbon::today()->addDays(rand(1, 365));Surplus
S
3

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.

Spiky answered 24/8, 2021 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.