我有以下几点

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

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

我需要使用什么函数?


当前回答

这种格式非常适合于标准字符串比较。

if ($date1 > $date2){
  //Action
}

要以这种格式获取今天的日期,只需使用:date("Y-m-d H:i:s")。

So:

$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";

if ($date < $today) {}

这就是这种格式的美妙之处:它很好地排序。当然,这可能会降低效率,这取决于您的具体情况,但它也可能更方便,并导致更可维护的代码-我们需要了解更多才能真正做出判断。

对于正确的时区,您可以使用,例如,

date_default_timezone_set('America/New_York');

点击这里查看可用的PHP时区。

其他回答

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

你可以使用DateTime类:

$past   = new DateTime("2010-01-01 00:00:00");
$now    = new DateTime();
$future = new DateTime("2021-01-01 00:00:00");

比较运算符工作*:

var_dump($past   < $now);         // bool(true)
var_dump($future < $now);         // bool(false)

var_dump($now == $past);          // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future);        // bool(false)

var_dump($past   > $now);         // bool(false)
var_dump($future > $now);         // bool(true)

也可以从DateTime对象中获取时间戳值并进行比较:

var_dump($past  ->getTimestamp());                        // int(1262286000)
var_dump($now   ->getTimestamp());                        // int(1431686228)
var_dump($future->getTimestamp());                        // int(1577818800)
var_dump($past  ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)

*注意===在比较两个不同的DateTime对象时返回false,即使它们表示相同的日期。

试试这个:

if (date("Y-m-d",strtotime($funding_dt)) >= date("Y-m-d",strtotime('31-01-2007')))
{
    echo "ok";
} else {
    echo "not";
}

比较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');
}
$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