我想根据投票结束日期时间在 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:i
在 this page 上工作.
关于javascript - 如何使用存储在值中的 am/pm 使 PHP 倒计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541280/