需要修改日期倒计时的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':'');}
答案 0 :(得分:1)
您需要检查差异是正面还是负面。由于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!
}
答案 1 :(得分:1)
有很多方法可以做到这一点......
我认为更简单的是:
$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做,并把一个漂亮的秒计数器!
答案 2 :(得分:0)
试试这个:
<?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':'');}
}
因此,如果当前日期大于倒计时日期,则根本不做任何事情。