使用 php 根据截止日期突出显示行

Row highlighting based on due date using php

我对 PHP 比较陌生,我已经学习了程序 PHP,并且正在使用一个应用程序。

我浏览了该网站,发现了一些使用 PHP、HTML 和 CSS 进行日期格式化和突出显示的示例。

借助此处的帮助和 PHP 手册,我整理了一些代码以突出显示遵循此标准的数据库提供的许​​多其他行中的 2 个不同行:

这是我整理的代码

//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));

//Database entry for comparison
$due = date_create($record['projected_delivery']);

$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);

//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);

if ($diffThree->format('%d') < 3) {
   $highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
   $highlight_css = " danger";
}else {
   $highlight_css = "";
}

然后我将 $highlight_css 添加到 HTML。

到目前为止 一些 功能正在运行。未添加正确的突出显示:

如何实现这个功能?

$diffThree->format('%d')

将return一个字符串而不是一个整数。为了将它与其他数字(在您的情况下为 3 和 1)正确比较,您需要将其转换为 int:

(int) $diffThree->format('%d')

(int) $diffOne->format('%d')

我会改用这个:

<?php

$dueDates =["06/05/2017","06/06/2017","06/07/2017","06/08/2017","06/09/2017","06/10/2017","06/11/2017","06/12/2017"];
$table = "<table class='table table-bordered'><thead><tr><th>Date</th></tr></thead><tbody>";
$today = date_create(date('m/d/Y')); // example: 06/07/2017
foreach ($dueDates as $dueStr) {
    $due = date_create($dueStr);
    $diff = date_diff($today, $due)->format("%r%a");
    $highlight_css = "";
    if ($diff > 1 && $diff <= 3) {
        $highlight_css = " warning";
    } elseif ($diff == 1) {
        $highlight_css = " danger";
    }
    $table .= "<tr class='$highlight_css'><td>$dueStr</td></tr>";
}
$table .= "</tbody></table>";
?>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
<?php
echo $table;

问题

A DateInterval (the return value of date_diff()) has the number of days (actually stored in a property d, which could be used instead of getting a string with format()), which should always be a positive number. And for dates before today's date, the first date diff (i.e. $diffOne) will be 2+ days and the second date diff (i.e. $diffThreeDays) will be 4+ (see this playground example,调试输出高于 table),因此今天日期之前的天数永远不会与“warning”或“danger' 根据给定的逻辑。

一个解决方案

比较日期的一种方法(可能更简单)是使用 DateTime comparison

Note:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.1

所以比较日期时间变量(即 $due$dueOneDay$dueThreeDays)而不是日期差异。

在下面的逻辑中,你会注意到比较的顺序被颠倒了,所以一天差异的检查在三天差异的检查之前,以避免危险情况永远不会发生。

if ($due < $dueOneDay){
   $highlight_css = " danger";
}else if ($due <= $dueThreeDays) {
   $highlight_css = " warning";
}else {
   $highlight_css = "";
}

使用这种方法,不需要 date_diff 变量(即 $diffOne$diffThree)。

请参阅 this playground example 中的演示。


1http://php.net/manual/en/datetime.diff.php#example-2524