【问题标题】:How do I generate a random time interval and add it to a mysql datetime using php?如何生成随机时间间隔并将其添加到使用 php 的 mysql 日期时间?
【发布时间】:2011-01-15 06:11:24
【问题描述】:

我在 mysql 表中有很多行,日期时间格式为:

2008-12-08 04:16:51 etc

我想生成一个介于 30 秒和 3 天之间的随机时间间隔,并将它们添加到上述时间。

a) 如何生成 30 到 3 天之间的随机时间?

b) 如何将这个时间添加到上面的日期时间格式中?

我想我需要做一个循环来提取所有信息,在 php 中进行数学运算,然后更新行...

有什么想法吗?

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    使用 MySQL 的 rand() 函数:

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

    将在 0 秒到三天之间为您提供当前日期时间 +。

    【讨论】:

      【解决方案2】:

      更简单的方法。

      $new_date = date('Y-m-d h:i:s', strtotime('2008-12-08 04:16:51 +'.rand(30, 60 * 60 * 24 * 3).' seconds'));
      

      【讨论】:

      • 哇...我在尝试 $rand_sec = rand(1,60); $rand_min = 兰德(1,60); $rand_hour = 兰德(1,12); $rand_day = 兰德(1,30); $conf_time = strtotime('+ ' . $rand_day . 'day ' . $rand_hour . ' hours ' . $rand_min . ' minutes . ' . $rand_sec . ' seconds', $row['dateAdded']);但它不像你的那样工作。谢谢!
      • 奇怪的是,我注意到有些日期设法计算出比原始时间更早的时间......这对我来说似乎是不可能的??即 2008-12-08 04:16:36 是 1 个原始时间,计算出来的第二个时间是 2008-12-08 04:13:16。怎么会这样?
      • 嗯,奇怪。也许在同一个字符串中有一个相对和复合格式会搞砸它。你可以试试这个 $new_date = date('Y-m-d h:i:s', strtotime('+'.rand(30, 60 * 60 * 24 * 3).' seconds', strtotime('2008-12-08 04:16:51')));
      • hmmm...谢谢...我仍然比原来的时间少。这很奇怪!
      • 在 23,000 行中,大约 2,000 行的第二次比第一次少。
      【解决方案3】:

      您能否使用随机的 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
      ...
      

      这可能不是最有效的解决方案,但应该可以。

      【讨论】:

      • 注意 - OP 要求“30 秒到 3 天之间”,而不是 3-30 天。
      • 嘿,没注意到。不过已经修复了。
      猜你喜欢
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2013-02-05
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多