I am working on a project where users can post/apply to jobs. if a user post a job with 2 days delivery time. I'm adding 2 days in the current time when inserting into database. then I am showing a countdown to user that shows how many days, hours, minutes, seconds are left both with PHP and Javascript. but the Javascript is 5 hours behind from the PHP. I have asked question about this and the users told me: It looks like a timezone difference issue. and I have to store and manipulate dates in UTC.
For PHP to use UTC I did: date_default_timezone_set('UTC');
For Mysql: UTC_TIMESTAMP() + INTERVAL " . $job['delivery_time'] . "
For Javascript: var endDate = new Date("<?php echo $job['job_expiration']; ?>");
But still the timer is 5 hours behind from PHP, Mysql.
"INSERT INTO jobs(job_expiration) VALUES(UTC_TIMESTAMP() + INTERVAL " . $job['delivery_time'] . ")";
like so.
I'm using UTC_TIMESTAMP
and NOW()
so I can select the jobs where time is less than four hours without selecting all jobs.
How can I solve this?
<?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');
}
}
Here is the Javascript code:
// $job['job_expiration'] = 2020-05-17 13:30:24
function countdownTimer() {
// original code
//const difference = +new Date("<?php echo $job['job_expiration']; ?>") - +new Date();
// modified for stackoverflow
const difference = +new Date("2020-05-17 13:30:24") - +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);
<div id="countdown"></div>