比较2个日期和当前年份

时间:2017-01-29 06:13:57

标签: php

我正在比较2个日期并检查当前项目是否已过期。在某些情况下工作正常,但我需要的是与当前年份进行比较。

$time_before = strtotime('1-Apr-16');// from excel sheet date format
$date_before = date('y-m-d', $time_before);
$time_after = strtotime('31-May-16'); // from excel sheet date format
$date_after = date('y-m-d', $time_after); // 2016-12-31
echo "<br/><br/><br/><br/>";
$datetime1 = new DateTime($date_before);
$datetime2 = new DateTime($date_after);
if($datetime1>$datetime2){echo "expired";}else{echo "active";}

Use Case1:
$time_before = '01-04-16';
$time_after = '31-05-16';
Result=active //where as it what I am expecting to return expired since 2016 is passed.

Use Case2:
$time_before = '28-01-17';
$time_after = '28-02-17';
Result=expired //working fine.

1 个答案:

答案 0 :(得分:0)

构造函数参数格式错误。 new DateTime('31-05-16');后,实例将代表2031-05-16之类的日期。

当您确定日期格式时,使用createFromFormat方法创建DateTime的新实例,然后与其他实例进行比较。

示例

 //Enter your code here, enjoy!

$time_before = '01-04-16';
$time_after = '31-05-16';

$datetime1 = \DateTime::createFromFormat('d-m-y', $time_before);
$datetime2 = \DateTime::createFromFormat('d-m-y', $time_after);

<强>测试

$time_before = '01-04-16';
$time_after = '31-05-16';

$datetime1 = \DateTime::createFromFormat('d-m-y', $time_before);
$datetime2 = \DateTime::createFromFormat('d-m-y', $time_after);

\assert(
    $datetime1 < $datetime2,
    "Project is expired"
);    

$time_before = '28-01-17';
$time_after = '01-01-17';

$datetime1 = \DateTime::createFromFormat('d-m-y', $time_before);
$datetime2 = \DateTime::createFromFormat('d-m-y', $time_after);

\assert(
    $datetime1 > $datetime2,
    "Project is active"
);