0

需要修改日期倒计时的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':'');}
4

3 回答 3

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来做,也可以放一个漂亮的秒计数器!

于 2013-09-24T03:38:23.570 回答
1

您需要检查差异是正面的还是负面的。由于该diff方法返回 a 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!
 }
于 2013-09-24T03:35:12.623 回答
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':'');}
}

因此,如果当前日期大于倒计时日期,则根本不做任何事情。

于 2013-09-24T03:32:51.120 回答