Search code examples
javascriptjquerycountdown

create countdown based on server hour


I´m facing a need of creating a coundown to display when ever a certain promo will be over, all i have is front-end access via google tag manager, first i manage to get the server hour with js, now i need to set the countdown hour based on the server hour and not local hour.

 <script>
  // it´s giving the correct hour
  var getserver = new Date();
 getserver.setHours(getserver.getHours());
 var newtets = getserver.toUTCString();
 alert(newtets);



 // using a basic countdown
   var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();

  // Update the count down every 1 second
 var x = setInterval(function() {

// Get todays date and time
var now = new Date().getTime();
/* 
 var now = new Date();
now.setHours(now.getHours());
var newnow = now.toUTCString();
i tried to replace now with newnow but is not working, how can i transform this
*/


// Find the distance between now an the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";

// If the count down is over, write some text 
if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);

</script>

var now = new Date().getTime(); is what getting the time and use it to countdown, this is taking local time, how can i get var now = new Date().getTime(); to be server hour, which i obtained with the 1 script


Solution

  • The only way to get your updated server hour is using an ajax call. The problem is that the request to the server is not immediate so you will have a delay.

    Maybe it would be better to get the user timezone and calculate the promo ending with this information.

    You can get the user timezone offset using:

    var offset = new Date().getTimezoneOffset();