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);
It looks like a timezone difference issue.
If you enter a string like "2020-05-13 15:24:22" into Date()
, it assumes that string is in the timezone of the computer.
For example, my computer is in the Pacific daylight (GMT - 7) time zone:
let date1 = new Date("2020-05-13 10:56:50");
console.log(date1); // '2020-05-13T17:56:50.000Z'
Notice that Date
converted my Pacific daylight time to UTC, 7 hours later.
If you simply call Date()
without any argument, you will get the current date and time in UTC timezone:
let date2 = new Date();
console.log(date2); // '2020-05-12T17:57:36.088Z'
It's hard to tell for sure from the example, but it's very likely that the PHP time:
<?php echo $job['job_expiration']; ?>
is in the server's timezone, but the JavaScript is running on a client computer with a different timezone.
A good rule to keep from messing up timezones is to always store and manipulate dates in UTC, then convert them to local time only for display.
And if you're using a string as an argument to new Date
, ensure the string is in UTC time:
let date = new Date('2020-05-12T17:56:50.000Z');
The trailing 'Z' indicates this date string is in UTC ("zulu") timezone.