需要修改日期倒计时的PHP代码(当计数达到0时希望不显示任何内容)
我使用以下代码显示特定日期的文本视觉对象倒计时,分为月、周、天。效果很好。但是,当倒计时达到实际事件日期然后超过事件日期时,它仍然显示绝对差异。我希望代码此时不显示任何内容(没有输出到屏幕)。我将不胜感激有关如何修改此内容的一些指导要执行的代码,如说明所示。
$d1 = new DateTime(); // now
$d2 = new DateTime('2014-01-08'); // set the date +1 to compensate for 1-day
error in script
$diff = $d2->diff($d1);
list($y,$m,$d) = explode('-', $diff->format('%y-%m-%d'));
$months = $y*12 + $m;
$weeks = floor($d/7);
$days = $d%7;
printf('Countdown To Event - ');
if ($months) {printf('%d month%s ', $months, $months>1?'s':'');}
if ($weeks) {printf('%d week%s ', $weeks, $weeks>1?'s':'');}
if ($days) {printf('%d day%s ', $days, $days>1?'s':'');}
您需要检查差异是正数还是负数。由于 diff
方法返回一个 DateInterval
,因此可以检查 invert
属性。
$d1 = new DateTime(); // now
$d2 = new DateTime('2014-01-08');
$diff = $d2->diff($d1);
if ($diff->invert == 1) // the countdown is running
{
list($y,$m,$d) = explode('-', $diff->format('%y-%m-%d'));
$months = $y*12 + $m;
$weeks = floor($d/7);
$days = $d%7;
printf('Countdown To Event - ');
if ($months) {printf('%d month%s ', $months, $months>1?'s':'');}
if ($weeks) {printf('%d week%s ', $weeks, $weeks>1?'s':'');}
if ($days) {printf('%d day%s ', $days, $days>1?'s':'');}
}
else
{
// The countdown finished, do something!
}
有很多方法可以做到这一点...
我认为更简单的是:
$FinalDate='2013-09-23';
$d1 = new DateTime(); // now
$d2 = new DateTime($FinalDate); // set the date +1 to compensate for 1-day
$diff = $d2->diff($d1);
list($y,$m,$d) = explode('-', $diff->format('%y-%m-%d'));
$months = $y*12 + $m;
$weeks = floor($d/7);
$days = $d%7;
if(strtotime($FinalDate)>time()){
printf('Countdown To Event - ');
if ($months) {printf('%d month%s ', $months, $months>1?'s':'');}
if ($weeks) {printf('%d week%s ', $weeks, $weeks>1?'s':'');}
if ($days) {printf('%d day%s ', $days, $days>1?'s':'');}
}else{
echo "Actions AFTER the date";
}
但是这段代码看起来真的很糟糕,你可以做得更好。你可以用javascript来做到这一点,也可以放一个漂亮的秒计数器!
试试这个:
<?php
$d1 = new DateTime(); // now
$d2 = new DateTime('2014-01-08'); // set the date +1 to compensate for 1-day
$diff = $d2->diff($d1);
list($y,$m,$d) = explode('-', $diff->format('%y-%m-%d'));
if ($d1 < $d2) {
$months = $y*12 + $m;
$weeks = floor($d/7);
$days = $d%7;
printf('Countdown To Event - ');
if ($months) {printf('%d month%s ', $months, $months>1?'s':'');}
if ($weeks) {printf('%d week%s ', $weeks, $weeks>1?'s':'');}
if ($days) {printf('%d day%s ', $days, $days>1?'s':'');}
}
因此,如果当前日期大于倒计时日期,则根本不做任何操作。