Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply use subSeconds() to achieve this.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading