Gags Gags - 2 years ago 146
Javascript Question

Javascript Countdown Timer - not working as expected

I have an issue in displaying counter between 2 dates. I know the issue and it is that Timezone is

GMT+05:30



I need to know, how to rectify that


My Solution:

var start = new Date();
var end = new Date("2017-10-03"); // This date is coming from database as <?php echo $date_end; ?>

function getClock() {
var start = new Date();
var end = new Date("<?php echo $date_end; ?>");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}

setInterval('getClock()', 1000);


As start date is
02 Oct 10PM
and End date is
03 Oct
. So as per time calculation i shall get timer of
2 hours


but i am getting timer is 2hours+5:30 = 7:30 hours.

Please help in getting right timer.

JS Fiddle link is HERE

Answer Source

You can get the timezone offset from the end date after you construct it, and then use that to reassign the value.

Here is a related question.

You can use the code from that post as follows:

var end = new Date("<?php echo $date_end;  ?>");
end.setTime( end.getTime() + end.getTimezoneOffset()*60*1000 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download