我有以下几点

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

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

我需要使用什么函数?


当前回答

$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是否在最后一天内。

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

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

}
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);

(w3schools的例子,它工作完美)

扩展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上的第一篇文章!

根据我的经验,一个警告是,如果你的目的只涉及日期,那么要小心包括时间戳。例如,今天是“2016-11-09”。涉及时间戳的比较将使这里的逻辑无效。的例子,

//  input
$var = "2016-11-09 00:00:00.0";

//  check if date is today or in the future
if ( time() <= strtotime($var) ) 
{
    //  This seems right, but if it's ONLY date you are after
    //  then the code might treat $var as past depending on
    //  the time.
}

上面的代码似乎是正确的,但如果它只是你想比较的日期,那么,上面的代码不是正确的逻辑。为什么?因为,time()和strtotime()将提供包含时间戳。也就是说,即使两个日期在同一天,但时间上的差异也会有影响。请看下面的例子:

//  plain date string
$input = "2016-11-09";

因为输入是普通的日期字符串,在$input上使用strtotime()将假设这是2016-11-09的午夜。因此,run time()在午夜之后的任何时间都会将$input视为过去,即使它们是在同一天。

要解决这个问题,你可以简单地编写如下代码:

if (date("Y-m-d") <= $input)
{
    echo "Input date is equal to or greater than today.";
}