0

So I have created a countdown timer in JS but realized my clients site has GMT +2 on the time listing meaning that the counter is not counting down to the correct time.

Here is my JS and screenshot of the counter below.

$('.countdownListTimer').each(function (i, obj) {
        var startTime = $(this).attr("data-startTime");
        var today = new Date();

        const diffTime = Math.abs(startTime - today);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        var countdownListTimerId = $(this).attr("data-id");
        var countDownDate = new Date(startTime).getTime();
        var x = setInterval(function () {
            var now = new Date().getTime();
            var distance = countDownDate - now;
            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);


            $("#" + countdownListTimerId).html(days + "d " + hours + "h "  + minutes + "m ");

            if (days < 1) {
                $("#" + countdownListTimerId).html(hours + "h " + minutes + "m "/* + seconds + "s "*/);
            }
            if (hours < 1) {
                $("#" + countdownListTimerId).html(minutes + "m "/* + seconds + "s "*/);
            }
            //if (minutes < 1) {
            //    $("#" + countdownTimerId).html(seconds + "s ");
            //}
            if (distance < 1) {
                clearInterval(x);
                $("#" + countdownListTimerId).html("Ended");
            }
        }, 1000);
    });

screenshot of the site counter and time its reading from

1 Answers1

0

You should make sure that the countDownDate is calculated from a UTC specified date. So either make the "data-startTime" attribute a string that specifies a UTC date/time, or interpret it as such when you create the date object. The first idea is probably simpler:

For example the attribute could be:

data-startTime="2021-05-19T20:00:00.000Z"

So, to repeat, this would be the target time in the UTC time zone.

trincot
  • 317,000
  • 35
  • 244
  • 286