skip to Main Content

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

Answers


  1. You can simply use subSeconds() to achieve this.

    $randomDateTime = Carbon::now()->subSeconds(rand(0, 30 * 24 * 60 * 60));
    
    Login or Signup to reply.
  2. 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));

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search