Reputation: 3839
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
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
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
Reputation: 244
You can get the timezone offset from the end date after you construct it, and then use that to reassign the value.
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
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