How do I generate a random time interval and add it to a mysql datetime using php?
I have many rows in mysql table with datetime's in the for开发者_开发知识库mat 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?
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.
easier way.
$new_date = date('Y-m-d h:i:s', strtotime('2008-12-08 04:16:51 +'.rand(30, 60 * 60 * 24 * 3).' seconds'));
Would you be able to use a random unix timestamp and convert into the MySQL timestamp format? I would assume you could so something like:
$randomTime = time() + rand( 30, 86400 * 3 ); // since there are 86400 seconds in a day,
// this should generate a random time
// 3-30 days from now
$randomTimeString = date( "Y-m-d H:i:s", $randomTime ); // format the date (php.net/date)
$st = $mysqli->query( "...", $randomTimeString ); // insert it into the database
...
This probably isn't the most efficient solution, but it should work.
精彩评论