【问题标题】:Date comparison working as long as time is 00:00:00只要时间为 00:00:00,日期比较就有效
【发布时间】:2013-07-23 09:21:16
【问题描述】:

这是我的事件脚本,用于提取接下来 7 天的约会,它似乎可以正常工作,但仅在一种情况下........日期和时间以日期时间格式保存在 mysql 数据库中所以 2013-12-23 08:30:00 。我的脚本每天都会打印出来,并为要下车或取货的客户找到当天的约会。 mysql 会查看 db 并将客户与下车或取货字段匹配到打印的日期,并将它们添加到日期下方的 div 中。

我遇到的问题是,如果时间设置为 00:00:00 以外的任何时间,则当天不会接听该客户。如何让比较忽略时间而只使用日期?

            // Date box container
    echo '<div class="dateboxcontainer">';

    // Loop through and create a date for the next 7 days
    $days = new DatePeriod(new DateTime, new DateInterval('P1D'), 7); 
    foreach ($days as $day) {
    echo '<div class="datebox">';
    echo '<div class="topdate">';

          echo strtoupper($day->format('D d')) . PHP_EOL;
    echo '</div>';  

              // Get the names for each day
          $theday = strtoupper($day->format('Y-m-d'));    
          $sqldate = <<<SQL
        SELECT *
        FROM `jobdetails`
        WHERE datedroppingoff = '$theday' OR datepickingup = '$theday'
    SQL;
    if(!$resultdate = $db->query($sqldate)){
        die('There was an error running the query [' . $db->error . ']');
    }
    while($rowdate = $resultdate->fetch_assoc()){
        echo $rowdate['name'];
            }
         //

    echo '</div>';
    }  
    echo '</div>';
    //

【问题讨论】:

    标签: php date datetime for-loop while-loop


    【解决方案1】:

    您现在正在做的是将 date/time 值与 date 值进行比较。如果时间部分不是午夜,则此比较将失败。

    您可以通过使用DATE() MySql 函数将苹果与苹果进行比较来修复比较:

    WHERE DATE(datedroppingoff) = '$theday' OR DATE(datepickingup) = '$theday'
    

    还有其他方法可以做到这一点,例如

    WHERE DATEDIFF(datedroppingoff, '$theday') = 0 OR ...
    

    如果您手头有 $nextday 值,您也可以这样做

    WHERE (datedroppingoff >= '$theday' AND datedroppingoff < '$nextday') OR ...
    

    【讨论】:

    • 非常感谢!第一个完成这项工作:)
    【解决方案2】:

    您在 mySQL 中存储特定的时间和日期,但仅在 SQL 查询中搜索日期。由于 mySQL 不了解您要搜索完整的一天还是特定时间点之间的区别,因此 mySQL 假定您在 0:00:00 时间查找这一天。

    你有几个选项,你可以搜索一个时间段(伪代码,自己检查边界):

    WHERE datedroppingoff > '$theday' AND datedroppingoff < '$theday'+1
    

    另一种选择是将日期和时间存储在单独的数据库字段中。这样你就可以让你的 SQL 查询更简单。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2013-07-12
      • 2017-09-21
      • 1970-01-01
      • 2016-06-04
      相关资源
      最近更新 更多