【问题标题】:Comparing two dates in PHP and MYSQL比较 PHP 和 MYSQL 中的两个日期
【发布时间】:2016-10-17 05:53:22
【问题描述】:

我想在 PHP 中比较两个日期和时间值。第一个日期来自 MySQL,第二个是当前日期。我想在两个日期相同时运行一些代码。我尝试了下面的代码,但条件随时满足,这是错误的。

$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
    //I want to run some code here
}else{
}

代码有什么问题?在比较之前,我还尝试用strtotime() 隐藏两个日期,但它给了我同样的问题。即使两个日期不同,上述条件也随时满足。

【问题讨论】:

  • 您想比较它们的精确度是多少?最多几个小时?
  • 不,它不是重复的问题,我读了那个问题但没有得到我想要的答案,这就是我问新问题的原因。
  • 我想比较日期和时间(小时和分钟)。我不想比较秒数。
  • 你也这样比较: $var = $row['send_date']; if((时间()-(60*60*24)) == strtotime($var)){ ... }
  • $row['send_date'] 的输出是什么

标签: php mysql date


【解决方案1】:

一种方法是从 MySQL 获取 Unix timestamp(自 '1970-01-01 00:00:00' UTC 以来的秒数),然后对数字进行操作:

$row = get_db_row("SELECT UNIX_TIMESTAMP(send_date) AS send_date_ts
  FROM table WHERE $condition");
$hours = (int) ($row['send_date_ts'] / 3600);
$current_hours = (int) (time() / 3600);
if ($hours == $current_hours) {
  // current hour
}

时间戳很方便,因为:

  • 不需要考虑格式;
  • 对数字的运算通常更快;
  • 代码看起来更干净。

【讨论】:

    【解决方案2】:

    试试这个:

    $current_datetime = date('Y-m-d H:i');
    $send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
    if(strtotime($current_datetime) == strtotime($send_date)){
        //I want to run some code here
    }else{
    }
    

    希望对你有帮助!!!!

    【讨论】:

    • 你改变了什么?正确解释。
    • @AHJeebon :我确实将日期转换为 strtotime 格式,因为这是比较日期值的正确方法。
    • @KaushaThakkar :是的,这段代码对我来说运行良好。谢谢
    • @KetanLathiya 谢谢!!你能给它一个绿色的勾吗:)
    【解决方案3】:

    试试这个。在我的服务器上工作得很好我还有别的东西,因为它们不相等。我从数据库收到的日期是类型datetime 格式2015-04-13 09:03:49

    <?php
         $current_datetime = strtotime(date('Y-m-d H:i'));
         $send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
         if($current_datetime == $send_date){
             //I want to run some code here
             echo 'something';
         }else{ 
             echo 'something else';
         }
    

    输出:

    echo $current_datetime . '<br/>';
    2016-10-17 09:19
    
    echo $send_date .'<br/>';    
    2015-04-13 09:03
    
    // result
    something else
    

    【讨论】:

    • 您正在将字符串与整数进行比较,无法正常工作。 strtotime(date('Y-m-d H:i')) 永远不会等于 date("Y-m-d H:i", strtotime($row['send_date']))。
    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多