Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random time interval and add it to a mysql datetime using php?

Tags:

php

mysql

I have many rows in mysql table with datetime's in the format of:

2008-12-08 04:16:51 etc

I'd like to generate a random time interval of anywhere between 30 seconds, and 3 days and add them to the time above.

a) how do I generate a random time between 30 and 3 days?

b) how do I add this time to the date time format above?

I imagine i need to do a loop to pull out all the info, do the math in php, and then update the row...

Any ideas?

like image 614
willdanceforfun Avatar asked Feb 02 '26 07:02

willdanceforfun


1 Answers

Using MySQL's rand() function:

update [table] set [field] = now() + interval floor(rand()*(60*60*24*3)) second;

wil get you the current datetime + between 0 seconds and three days.

like image 58
klokop Avatar answered Feb 04 '26 21:02

klokop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!