从Day Hour Minute Second开始的PHP倒计时

时间:2017-02-17 11:15:13

标签: php countdown

想要显示剩余天数,小时数,分钟数,秒数。

时间数据采用以下格式:

startTime:" 2017-02-17T13:51:13",

我在堆栈上找到了一个示例脚本:

<?php
 $now  = new DateTime();
 $ends = new DateTime('May 31, 2017, 11:59 pm'); 
 $left = $now->diff($ends);
?>


<dd>
<div class="timer_wrp">Remaining
    <ul class="timer countdown">
        <li><i><?php echo $left->format('%a'); ?></i>Day</li>
        <li><i><?php echo $left->format('%h'); ?></i>Hour</li>
        <li><i><?php echo $left->format('%i'); ?></i>Min</li>
        <li><i><?php echo $left->format('%s'); ?></i>Sec</li>
    </ul>
</div>

日期格式不同,是否有一种简单的方法可以使用其当前设置的方式,还是必须将其更改为示例格式?你看到这个例子中可能缺少什么吗?感谢

1 个答案:

答案 0 :(得分:0)

检查此。如果您未设置时区,则您的计算可能是错误的。因为,默认情况下,它占用服务器时区。它可能还有其他解决方案,但就我而言,我始终使用javascript。

<?php

date_default_timezone_set("Asia/Calcutta");
$now  = new DateTime();
$ends = new DateTime('Oct 9, 2020, 4:40:00'); 
$left = $now->diff($ends);
?>


<div class="timer">

<p>Remaining </p>
<ul class="timer countdown">
    
    <li><i><?php echo $left->format('%a'); ?></i>Day</li>
    <li><i><?php echo $left->format('%h'); ?></i>Hour</li>
    <li><i><?php echo $left->format('%i'); ?></i>Min</li>
    <li><i><?php echo $left->format('%s'); ?></i>Sec</li>
    
</ul>
</div>

您可能还需要这个。这是用JavaScript编写的。复制两者并查看差异。

<p id="demo"></p>
<!--javascript-->
<script>
// Set the date we're counting down to
var countDownDate = new Date("Oct 9, 2020 4:40:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

// Get today's date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";

// If the count down is over, write some text 
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>