Search code examples
javascriptjquerycountdown

JS Countdown timer with hours/seconds not working in Safari


I have a countdown timer, which is working perfectly in Chrome, but not in Safari. I already found similar questions on SO, but could not find the solution for me.

If I remove the hours and seconds from the timestamp, it is also working in Safari, but I need it with hours/minutes.

  function makeTimer() {
    	datestamp = "2019-09-25 00:00";
        var endTime = new Date(datestamp);
        // var endTime = new Date("2019-09-25 00:00");
          endTime = (Date.parse(endTime) / 1000);

          var now = new Date();
          now = (Date.parse(now) / 1000);

          var timeLeft = endTime - 7200 - now;

          var days = Math.floor(timeLeft / 86400);
          var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
          var hours2 = Math.floor(((timeLeft - (days * 86400)) / 3600) + (days * 24));
          var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
          var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));

          if (hours2 < "0") { hours2 = "00"; minutes = "0"; seconds = "0"; $(".body").addClass("timerOff"); } else if (hours2 < "10") { hours2 = "0" + hours2; }
          if (minutes <= "0") { minutes = "00" } else if (minutes < "10") { minutes = "0" + minutes; }
          if (seconds <= "0") { seconds = "00" } else if (seconds < "10") { seconds = "0" + seconds; }

          $("#hours2").html(hours2);
          $("#minutes").html(minutes);
          $("#seconds").html(seconds);
      }

setInterval(function() { makeTimer(); }, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<span id="hours2"></span>h
<span id="minutes"></span>m
<span id="seconds"></span>s

Fiddle


Solution

  • According to MDN:

    A string value representing a date, specified in a format recognized by the Date.parse() method (these formats are IETF-compliant RFC 2822 timestamps and also strings in a version of ISO8601).

    In short, datestamp = "2019-09-25 00:00" is your wrong point. Changing the date to 2019-09-25T00:00:00Z should fix it.