hours/seconds 的 JS 倒数计时器在 Safari 中不起作用

JS Countdown timer with hours/seconds not working in Safari

我有一个倒数计时器,它在 Chrome 中运行良好,但在 Safari 中却不行。 我已经在 SO 上找到了类似的问题,但找不到适合我的解决方案。

如果我从时间戳中删除小时和秒,它也在 Safari 中工作,但我需要它 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

new Date 带有时间戳的构造函数是不鼓励的,因为它在浏览器之间不兼容。引用 mdn:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

有些浏览器会尝试解析日期,即使它不是标准格式。 Safari 不在这些浏览器中。

要获得跨浏览器的兼容性,请考虑使用 moment 或使用自定义函数解析字符串。

时刻:

moment(datestamp, 'YYYY-MM-DD hh:mm');

自定义函数:

function parseDate(str) {
   return str.match(/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2})/).slice(1, 6);
}

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).

总之,datestamp = "2019-09-25 00:00"是你的错误观点。将日期更改为 2019-09-25T00:00:00Z 应该可以解决问题。