【发布时间】:2011-01-15 06:11:24
【问题描述】:
我在 mysql 表中有很多行,日期时间格式为:
2008-12-08 04:16:51 etc
我想生成一个介于 30 秒和 3 天之间的随机时间间隔,并将它们添加到上述时间。
a) 如何生成 30 到 3 天之间的随机时间?
b) 如何将这个时间添加到上面的日期时间格式中?
我想我需要做一个循环来提取所有信息,在 php 中进行数学运算,然后更新行...
有什么想法吗?
【问题讨论】:
我在 mysql 表中有很多行,日期时间格式为:
2008-12-08 04:16:51 etc
我想生成一个介于 30 秒和 3 天之间的随机时间间隔,并将它们添加到上述时间。
a) 如何生成 30 到 3 天之间的随机时间?
b) 如何将这个时间添加到上面的日期时间格式中?
我想我需要做一个循环来提取所有信息,在 php 中进行数学运算,然后更新行...
有什么想法吗?
【问题讨论】:
使用 MySQL 的 rand() 函数:
update [table] set [field] = now() + interval floor(rand()*(60*60*24*3)) second;
将在 0 秒到三天之间为您提供当前日期时间 +。
【讨论】:
更简单的方法。
$new_date = date('Y-m-d h:i:s', strtotime('2008-12-08 04:16:51 +'.rand(30, 60 * 60 * 24 * 3).' seconds'));
【讨论】:
您能否使用随机的 unix 时间戳并将其转换为 MySQL 时间戳格式? 我会假设你可以这样:
$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
...
这可能不是最有效的解决方案,但应该可以。
【讨论】: