我有以下几点

$var = "2010-01-21 00:00:00.0"

我想将这个日期与今天的日期进行比较(即我想知道这个$var是否在今天之前或等于今天)

我需要使用什么函数?


当前回答

比较date - time对象:

(我选择了10天-任何超过10天的都是“旧”,否则是“新”)

$now   = new DateTime();
$yourdate = new DateTime("2021-08-24");
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
    echo "OLD! " . $yourdate->format('m/d/Y');
}else{
    echo "NEW! " . $yourdate->format('m/d/Y');
}

其他回答

扩展Josua在w3schools上的回答:

//create objects for the dates to compare
$date1=date_create($someDate);
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
//now convert the $diff object to type integer
$intDiff = $diff->format("%R%a");
$intDiff = intval($intDiff);
//now compare the two dates
if ($intDiff > 0)  {echo '$date1 is in the past';}
else {echo 'date1 is today or in the future';}

我希望这能有所帮助。我在stackoverflow上的第一篇文章!

要完成BoBby Jack,使用DateTime对象,如果你有php 5.2.2+:

if(new DateTime() > new DateTime($var)){
    // $var is before today so use it

}

给你:

function isToday($time) // midnight second
{
    return (strtotime($time) === strtotime('today'));
}

isToday('2010-01-22 00:00:00.0'); // true

另外,还有一些帮助函数:

function isPast($time)
{
    return (strtotime($time) < time());
}

function isFuture($time)
{
    return (strtotime($time) > time());
}
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');

var_dump(strtotime($today) > strtotime($expiry)); //false or true
strtotime($var);

将其转换为时间值

time() - strtotime($var);

给出自$var后的秒数

if((time()-(60*60*24)) < strtotime($var))

将检查$var是否在最后一天内。