PHP日期时间大于今天

时间:2015-09-18 01:20:53

标签: php date

请帮我解释我的代码有什么问题。它总是显示今天大于2016年2月1日? 2016年的地方大于2015年。

<?php
 $date_now = date("m/d/Y");

$date=date_create("01/02/2016");
$date_convert = date_format($date,"m/d/Y");

if ($date_now > $date_convert) {
        echo 'greater than';
    }else{
        echo 'Less than';
    }

P.S:01/02/2016来自我的数据库

2 个答案:

答案 0 :(得分:63)

比较日期。您正在比较字符串。在字符串比较的世界中,09/17/2015&gt; 01/02/2016因为09&gt; 01。您需要以可比较的字符串格式输入日期或比较可比较的DateTime个对象。

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

或者

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

答案 1 :(得分:0)

我们可以将日期转换成时间戳进行比较

<?php

    $date_now = time(); //current timestamp
    $date_convert = strtotime('2022-08-01');

    if ($date_now > $date_convert) {
        echo 'greater than';
    } else {
        echo 'Less than';
    }

?>