Gags
Gags

Reputation: 3839

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

Upvotes: 0

Views: 173

Answers (4)

EJAg
EJAg

Reputation: 3308

Make sure you pass year, month and day separately to initialize the date, so the system timezone is used, same as when you initialize your start date:

var end_str = "<?php echo $date_end;  ?>";
var arr = end_str.split("-")
arr = Date.new(arr[0], arr[1]-1, arr[2]); //month is 0-indexed

Upvotes: 0

Pv-Viana
Pv-Viana

Reputation: 642

Try something like this.

    setInterval(function(){
    var start = new Date();
    var end   = new Date("2017-10-03 00:00:00");
    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";
    }
}, 1000);

Upvotes: 1

Thomas5631
Thomas5631

Reputation: 244

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 );

Upvotes: 1

Olivier Liechti
Olivier Liechti

Reputation: 3188

The problem is because of the way Javascript handles timezones in the Date constructor (check out the documentation for details). If, instead of passing ("2017-10-03") you pass (2017, 9, 3), it should work. To avoid these kinds of problems, it is a good idea to always work in UTC.

Upvotes: 0

Related Questions