如何使用am / pm存储在PHP中的PHP倒计时?

时间:2018-01-31 11:39:59

标签: javascript php wordpress

我想根据投票结束日期时间在WordPress小部件中显示轮询倒计时。我能够将PHP变量传递给JavaScript文件,但它实际上并不像静态倒计时那样工作

1)我的HTML代码:

<P id="demo">

2)我的每次调用的倒计时JavaScript文件:

var countDownDate = new Date("February 21, 2018 16:19").getTime();

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

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an 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 ";

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

这样可以正常工作,但是我想让它也适用于我的动态值,我的PHP变量保持轮询结束日期时间为$poll_end_date,它给出的值类似于&#34; 2018年2月9日下午3:47&#34;。

如何根据此变量$poll-end-date值进行日,小时,薄荷倒计时。

1 个答案:

答案 0 :(得分:1)

您可以使用PHP DateTime类将日期转换为所需格式:

<?php
// The date for 'poll_end_date'
$date = 'February 9, 2018 3:47 pm';

// Parse the string based on the expected format
$dtime = DateTime::createFromFormat("F j, Y g:i a", $date);

// Output the date to match the required format
$timestamp = $dtime->format('F j, Y H:i');
?>

然后,您可以在通常的<script></script>标记内使用此PHP变量。

<script>
    var countDownDate = new Date("<?php echo $timestamp; ?>").getTime();
    // ... your script continues below
</script>

这些方法在这里有详细记载:

您可以阅读F j, Y H:i等日期格式如何在this page上运行。