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

标签 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 并且它给出的值类似于“February 9, 2018 年下午 3:47。

我如何根据这个变量 $poll-end-date 值对天、小时、薄荷进行倒计时。

最佳答案

您可以使用 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:ithis page 上工作.

关于javascript - 如何使用存储在值中的 am/pm 使 PHP 倒计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541280/

相关文章:

css - 如何在 WooCommerce 中将侧边栏从右侧移动到左侧?

php - WooCommerce 从前端隐藏订单项元(非管理员)

javascript - Tablesorter 将不会显示可排序的标题

java - 用户名和使用 AsyncTask 登录

php - MySQL multiple join, multiple sort maintain group

css - 如何将此媒体查询与特定 ID 结合起来

javascript - "static"在 React 中做什么?

javascript - 在 javascript 函数中执行 puppeteer 代码

asp.net - 解析来自磁条的信用卡输入

javascript - Protractor :非 Angular 登录到 Angular 站点