我有一些代码,允许用户输入“第一次考试”的日期,将该日期与今天的日期进行比较,如果这两个日期之间的差额是一定量,则显示警告/通知(因为其余的考试必须是在参加第一次考试的18个月内完成)。我在解决如何比较条件语句中的日期/日期之间的差异时遇到了麻烦-换句话说,如何将其$difference
与“ 18个月”或“ 2个月”进行比较,等等。正确的方向,将不胜感激。
代码:
<?php
// Set first exam date
$firstexamdate = "2015-08-20";
// Work out date that is 18 months from first exam date
$add_18_months = strtotime($firstexamdate . ' + 18 months');
$eighteen_months_time = date('Y-m-d',$add_18_months);
// Check
echo "Date of first exam: " . $firstexamdate . "<br>";
echo "18 months from this date: " . $eighteen_months_time . "<br>";
// Work out diff between cut-off date and today
$today = date('Y-m-d');
$date1 = new DateTime($eighteen_months_time);
$date2 = new DateTime($today);
$difference = $date1->diff($date2);
// Display
echo "Difference/time remaining: " . $difference->y . " years, " . $difference->m . " months, " . $difference->d . " days " . "<br";
// BELOW CODE NOT WORKING
// Display $difference as string
echo $difference->format('Y-m-d');
// Output correct warning colour
if ($difference <= /* 18 months */ and >= /* 6 months */ {
echo "Green warning: At least 6 months left.";
} elseif ($difference <= /* 5 months */ and >= /* 2 months */ {
echo "Orange warning: Less than 5 months left.";
} elseif ($difference <= /* 1 months */ and >= /* 0 months */ {
echo "Red warning: Less than one month left.";
}
?>
您可以使用$ difference对象的days属性:
if ($difference->days <= (18 * 30) && $difference->days >= (6 * 30) {
echo "Green warning: At least 6 months left.";
}
关于Php文档中的财产日:
如果DateInterval对象是由DateTime :: diff()创建的,则这是开始日期和结束日期之间的总天数。否则,天将为假。
http://php.net/manual/zh/class.dateinterval.php
编辑
如果您确切需要6个月和18个月,则可以使用以下方法:
$targetDate = new DateTime('20170529'); //here your target date;
$now = new DateTime(); //by default today;
$min = clone $targetDate;
$min->add(new DateInterval('P6M'));
$max = clone $targetDate;
$max->add(new DateInterval('P18M'));
if($now >= $min && $now <= $max){
// your code here
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句