0

I found the following function at how to countdown to a date

However, it is using the local machines time. This is not applicable to my case. It needs to be the server time.

I would like to pass the time to the JS from PHP, and then for this script to count on the remaining days, hours, minutes and seconds.

All the script above does is call a function at a set interval, then keep fetching the local time. Is it possible for it to count down on its own without getting the local machines time? What would that look like?

Is it better to use Javascript or jQuery for this?

CountDownTimer('08/19/2018 10:01 AM', 'countdown');
CountDownTimer('08/20/2017 10:01 AM', 'newcountdown');

function CountDownTimer(dt, id) {
  var end = new Date(dt);

  var _second = 1000;
  var _minute = _second * 60;
  var _hour = _minute * 60;
  var _day = _hour * 24;
  var timer;

  function showRemaining() {
    var now = new Date();
    var distance = end - now;
    if (distance < 0) {

      clearInterval(timer);
      document.getElementById(id).innerHTML = 'EXPIRED!';

      return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor((distance % _day) / _hour);
    var minutes = Math.floor((distance % _hour) / _minute);
    var seconds = Math.floor((distance % _minute) / _second);

    document.getElementById(id).innerHTML = days + 'days ';
    document.getElementById(id).innerHTML += hours + 'hrs ';
    document.getElementById(id).innerHTML += minutes + 'mins ';
    document.getElementById(id).innerHTML += seconds + 'secs';
  }

  timer = setInterval(showRemaining, 1000);
}
<div id="countdown"></div>
<div id="newcountdown"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nikk
  • 7,384
  • 8
  • 44
  • 90
  • Well, where it has a date, as in `CountDownTimer('date...` you'd output the date from PHP instead, echoing out the appropriate value. The PHP manual has a chapter about how to parse dates. – adeneo Aug 09 '17 at 20:09
  • No. The ` CountDownTimer('date...` is the date it will be counting down to. It gets the current time here `var end = new Date(dt);` but that function keeps refreshing each `setInterval(showRemaining, 1000);` and get the machine time. @adeneo – Nikk Aug 09 '17 at 21:42
  • https://jsfiddle.net/mplungjan/er4a525a/ – mplungjan Aug 10 '17 at 19:07
  • @mplungjan Why do we care what the client time is? It should only count down from the server time, regardless of the client time. – Nikk Aug 10 '17 at 23:11
  • But the script runs on the client so we only have the server time at load time - then we get the difference at load time and apply it in the loop every time – mplungjan Aug 11 '17 at 03:37
  • @mplungjan So whatever timezone they are at, the countdown will remain the same for every user? Does the server time need to be supplied in UTC or the original timezone? – Nikk Aug 11 '17 at 10:22
  • UTC is likely a good idea – mplungjan Aug 11 '17 at 20:32

0 Answers0