PHP日期时间比今天更大


PHP date time greater than today

请帮助我的代码有什么问题?它总是返回今天的日期大于'01/02/2016',其中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来自于数据库

不是比较日期。您正在比较字符串。在字符串比较的世界里,09/17/2015> 01/02/2016是因为09> 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';
}

演示

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");
if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}
演示

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

<?php
    $date_now = time(); //current timestamp
    $date_convert = strtotime('2022-08-01');
    if ($date_now > $date_convert) {
        echo 'greater than';
    } else {
        echo 'Less than';
    }
?>

日期可以是不同的格式,因此在比较之前最好将它们转换为时间戳

<?php
 $today = date("Y-m-d"); //Today
 $date = '2022-06-30'; //Date
 if (strtotime($today) > strtotime($date)) {
    echo 'Today is greater than date';
 }else{
    echo 'Today is less than date';
}