【问题标题】:Comparing time from mysql to time() in php在php中比较从mysql到time()的时间
【发布时间】:2014-03-20 08:16:53
【问题描述】:

我需要帮助。这是该链接在上午 7:00 到上午 7:30 可用的场景,该时间来自 mysql 数据库。

StartTime = 2014-03-19 07:00:00

EndTime = 2014-03-20 07:30:00

我尝试将其转换为 php 中的 strtotime()。

这是我的代码

$date_s = new DateTime($row->StartDate);

$date_e = new DateTime($row->EndDate);

$g = date("Y-m-d H:i:s");

<?= strtotime($date_s->format('Y-m-d H:i:s')) > strtotime($g) && strtotime($date_e->format('Y-m-d H:i:s')) < strtotime($g) ? "true" : "false"; ?>

结果总是让我失望,大约 1 小时前我在堆栈。任何人都可以帮忙吗? :D

【问题讨论】:

    标签: php mysql datetime unix-timestamp


    【解决方案1】:

    您可以直接比较 DateTime 对象:

    $date_s = new DateTime($row->StartDate);
    $date_e = new DateTime($row->EndDate);
    $now = new DateTime();
    
    if ($now > $date_s && $now < $date_e) {
    
    }
    

    或者不使用 DateTime 对象:

    $date_s = strtotime($row->StartDate);
    $date_e = strtotime($row->EndDate);
    $now = time();
    
    if ($now > $date_s && $now < $date_e) {
    
    }
    

    使用其中之一,但不能同时使用。

    【讨论】:

      【解决方案2】:

      MySQL 具有将日期转换为/从 unix 时间戳转换的函数。

      FROM_UNIXTIME() http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime

      UNIX_TIMESTAMP() http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

      也许您可以从查询中返回时间戳值。

      SELECT fields, UNIX_TIMESTAMP(date_field) FROM table ...
      

      【讨论】:

        【解决方案3】:

        以下代码可能对您有所帮助

        <?php
        $now = time();
        $starttime = "2014-03-19 07:00:00";
        $endtime = "2014-03-20 07:30:00";
        if($now > strtotime($starttime) && $now < strtotime($endtime)){
            //do something
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-26
          • 1970-01-01
          相关资源
          最近更新 更多