我正在尝试制作倒数计时器。我正在使用 PHP 和 Javascript。我面临的问题是时差显示比 php 晚了一段时间。如果 PHP 显示 19 小时,则 Javascript 显示 16 小时。
我的函数显示与 PHP 的时差
$timestamp = strtotime($time['expiration']) - time();
function convert_timestamp_to_date($timestamp)
{
$date1 = new DateTime("@0");
$date2 = new DateTime("@$timestamp");
if ($date1->diff($date2)->d < 1) {
return $date1->diff($date2)->format('%h Hours');
} else {
return $date1->diff($date2)->format('%a Days');
}
}
我的函数用 Javascript 显示时差
// $job['job_expiration'] = 2020-05-13 15:24:22
function countdownTimer() {
const difference = +new Date("<?php echo $job['job_expiration']; ?>") - +new Date();
let remaining = "Time's up!";
if (difference > 0) {
const parts = {
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
minutes: Math.floor((difference / 1000 / 60) % 60),
seconds: Math.floor((difference / 1000) % 60)
};
remaining = Object.keys(parts)
.map(part => {
if (!parts[part]) return;
return `${parts[part]} ${part}`;
})
.join(" ");
}
document.getElementById("countdown").innerHTML = remaining;
}
countdownTimer();
setInterval(countdownTimer, 1000);
当年话下