0

The following code counts down to specific hour setHours and then restarts the 24-hour countdown after that time. However, it takes the time off the user's computer so it'd be inaccurate in every country. How do I specify a timezone to the code so it's correct no matter where you are located?

<script>
    (function () {
        var start = new Date;
        start.setHours(14, 0, 0); // 2pm

        function pad(num) {
            return ('0' + parseInt(num)).substr(-2);
        }

        function tick() {
            var now = new Date;
            if (now > start) { // too late, go to tomorrow
                start.setDate(start.getDate() + 1);
            }
            var remain = ((start - now) / 1000);
            var hh = pad((remain / 60 / 60) % 60);
            var mm = pad((remain / 60) % 60);
            var ss = pad(remain % 60);
            document.getElementById('time').innerHTML =
                hh + 'hrs&nbsp;' + mm + 'mins&nbsp;' + ss + 'secs';
            setTimeout(tick, 1000);
        }

        document.addEventListener('DOMContentLoaded', tick);
    })();
</script>`
fjc
  • 5,590
  • 17
  • 36
Chris Gwynne
  • 47
  • 2
  • 7
  • 1
    Something like https://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp – Shardj May 21 '19 at 11:17
  • Its technically not inaccurate since it is showing the user the time in his own computer. Since the code is run on the user's computer, it'll be accurate everywhere. – SoWhat May 21 '19 at 11:17
  • Would something like `getTimezoneOffset` work? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset – Vasil Dininski May 21 '19 at 11:17
  • Possible duplicate of [Create a Date with a set timezone without using a string representation](https://stackoverflow.com/questions/439630/create-a-date-with-a-set-timezone-without-using-a-string-representation) – Oliver Nybo May 21 '19 at 11:37

1 Answers1

1

If you want the start time to be the same all over the world you can set it based on UTC time.

start.setHours(14 - start.getTimezoneOffset()/60, 0, 0);
Oleg
  • 6,124
  • 2
  • 23
  • 40