简体   繁体   English

PHP比较日期<=和> =不能正常工作

[英]PHP compare dates <= and >= doesn't work properly

I am trying to compare two date strings of type d/m/y, but it seems that something with the comparison of that type of dates doesn't work. 我正在尝试比较两个类型为d / m / y的日期字符串,但似乎无法与这种类型的日期进行比较。 I thought to use DateTime PHP's function, but at first I want to learn why the script above doesn't work. 我以为可以使用DateTime PHP的功能,但是起初我想了解为什么上面的脚本不起作用。

Here is the code: 这是代码:

public function listActiveNews(){

    $today = strtotime(date('d/m/Y'));

    $db = mysql_init();
    $sql = "SELECT * FROM ph_news WHERE newActive = 1";
    $prq = $db->prepare($sql);
    $prq->execute();


    foreach($prq->fetchAll(PDO::FETCH_ASSOC) as $fetch){

        $dateFrom = strtotime($fetch['newsDateFrom']);
        $dateUntil = strtotime($fetch['newsDateUntil']);

        if ( ($today >= $dateFrom) && ($today <= $dateUntil) ){

            print date('d/m/Y') . " >= " . $fetch['newsDateFrom'] .
                  " && " . date('d/m/Y') . " <= " .
                  $fetch['newsDateUntil'] ."<br>" ;
            print $fetch['Title'];
        }
    }
}

I am getting this result and I cannot understand why the comparison of these dates returns TRUE in the if clause. 我得到这个结果,我不明白为什么这些日期的比较在if子句中返回TRUE。

Output: 输出:

28/02/2014 >= 20/03/2014 && 28/02/2014 <= 27/02/2014 2014年2月28日> = 2014年3月20日&& 2014年2月28日<= 2014年2月27日
Title 标题

Here are the dates values: 以下是日期值:

date('d/m/Y') = 28/02/2014
$newsDateFrom = 20/03/2014
$dateUntil  = 27/02/2014

Really... stop abusing the date system. 真的...停止滥用日期系统。 $today = strtotime(date('d/m/Y')); is utterly pointless. 毫无意义。 $today = time() is the less convoluted and far more efficient version. $today = time()是复杂程度较低且效率更高的版本。

Plus, why are you doing the time filtering in PHP when you could simply do it in MySQL? 另外,为什么只可以在MySQL中进行时间过滤,却为什么要在PHP中进行时间过滤?

SELECT *
FROM ph_news
WHERE (newActive = 1) AND (curdate() BETWEEN newsDateFrom AND newsDateUntil)

will fetch only the records you actually want. 将仅获取您实际想要的记录。 Right now you're fetching pretty much the entire table, and then throwing away most everything except the few records you really did want. 现在,您将获取整个表的几乎所有内容,然后丢弃除您真正想要的几条记录以外的大多数所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM