PHP 检查日期是否已过


php check if date has passed

>我正在从Wordpress字段中获取日期,我需要检查日期是否已经过去了或还没有到来。

    $dates = ['date'=>'02/12/13','date'=>'10/12/14','date'=>'14/01/15'];

    foreach ($dates as $date){
        $the_date = $date['date'];

        echo $the_date;
        echo "  ";
        echo date('d/m/y');
        echo "  ";
        if($the_date < date('d/m/y')){
            echo 'gone';
        }else{
            echo 'to come';
        }
    }

福尔奇附和道。

    02/12/13 22/11/14 gone
    10/12/14 22/11/14 gone
    14/01/15 22/11/14 gone
    27/01/15 22/11/14 to come
    10/02/15 22/11/14 gone

看起来它只是在检查第一天的日期。

更好的选择是使用 DateTime 类。它允许使用比较运算符比较两个日期时间实例。

$dates = ['02/12/13','10/12/14','14/01/15'];
foreach ($dates as $date) {
    $the_date = 'DateTime::createFromFormat('d/m/y', $date);
    $now = new 'DateTime();
    echo $date." ".($the_date < $now ? 'gone' : 'to come')."'n";
}

您看到的问题是因为日期被比较为字符串。当前日期为"22/11/14",因此它将大于以"1"或"0"开头的任何其他日期。

PD:你的数组包含许多使用相同的"date"键的元素。这是一个问题,所以我在我的示例中删除了它们。

<?php
$dates = array('02/12/13','10/12/14','14/01/15');
$now = mktime(0,0,0);
foreach($dates as $date) {
  $tmp = explode('/',$date);
  $date_time = mktime(0,0,0,intval($tmp[1]),intval($tmp[0]),intval($tmp[2]));
  echo $date . ' ' . ($now > $date_time?'gone':'to come') . "'n";
}

使用 PHP 的 DateTime API:

$date='02/12/13';
if('DateTime::createFromFormat('d/m/y',$date) < new 'DateTime()){
//date is in the past
}else{
//date is either today or in the future
}

官方 PHP 文档:

http://php.net/manual/en/class.datetime.php

最好的方法是使用时间戳: 试试这个:

foreach ($dates as $date){
    $the_date = $date['date'];

    echo $the_date;
    echo "  ";
    echo date('d/m/y');
    echo "  ";
    if( strtotime($the_date) < time() )
    {
        echo ' is gone';
    }
    else
    {
        echo ' is to come';
    }
}

保持简单:

// $date is the date you need to compare to today
$date = ("2015 10 03");
// Make sure their formats are purely numeric and match
if ($date->format('m.d.y') >= date('m.d.y'))
{
   your procedure...
}

我建议改用DateTime类的功能。然后,您可以按如下方式进行检查:

<?php
$then = $reset_date;
$then = new DateTime($then);
$now = new DateTime(date("m-d-Y"));
$sinceThen = $then->diff($now);
$new = new DateTime($reset_date);
$old = new DateTime(date("m-d-Y"));
if ( $old->modify('+1 year') < $new) {
    echo "<font color='red'>Reset now <br></font>";
    echo "<font color='orange'>$sinceThen->y years <br></font>";
    echo "<font color='orange'>$sinceThen->m months </font>";
    echo "<font color='orange'>$sinceThen->d days have passed.<br></font>";
} else {
    echo "<font color='green'> $sinceThen->y years <br>
          $sinceThen->m months  $sinceThen->d days till to Reset.</font>";
    //Combined
 }
?>