我正在尝试制作倒数计时器。我正在使用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');
}
}
我的函数与Java脚本显示时差
// $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);
它看起来像是时区差异问题。
如果您在Date()
中输入类似“ 2020-05-13 15:24:22”的字符串,则假定该字符串位于计算机的时区中。
我的计算机在太平洋白天区域:
let date1 = new Date("2020-05-13 15:24:22");
console.log(date1); // '2020-05-13T22:24:22.000Z'
注意,它在7小时后将太平洋时间转换为UTC。
如果您不带任何参数简单地调用Date()
,您将获得UTC时区的当前日期和时间:
let date2 = new Date();
console.log(date2); // '2020-05-12T17:56:02.003Z'
很难从您的示例中看出来,但可能是PHP时间:
$job['job_expiration']
不在UTC时区。
避免弄乱时区的一个好规则是始终在UTC中存储和操纵日期时间,然后将其转换为本地时间以进行显示。