I'm trying to make a countdown timer. I'm working with PHP and Javascript. the problem I'm facing is the time difference shows is some time behind from php. if PHP show 19 hours then Javascript shows 16 hours.
My function that shows the time difference with 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');
}
}
My function that shows the time difference with 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);