You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS倒计时计时器在平板/手机显示NaN失效,桌面正常求排查

问题排查:移动端倒计时显示NaN的原因及修复方案

我来帮你搞定这个问题!你的倒计时脚本在桌面端正常但移动端出NaN,核心原因是日期字符串解析的浏览器兼容性差异,具体分析和修复方法如下:

可能的故障原因

  • 非标准时间格式导致解析失败:你写的"Dec 08, 2019 24:00:00 GMT-0500"里,24:00不是合法的时间表示(标准时间范围是00:00~23:59),桌面端浏览器可能会容错解析,但移动端浏览器(比如iOS Safari)对这种格式的兼容性很差,直接返回Invalid Date,导致countDownDate变成NaN,后续所有计算结果自然都是NaN。
  • 日期字符串格式的跨浏览器差异:不同浏览器对非ISO标准的日期字符串解析规则不一致,移动端的WebView或浏览器往往对格式要求更严格,不像桌面端Chrome/Firefox有较强的容错性。

修复方案

解决思路是用兼容性最好的日期构造方式,避免依赖浏览器对模糊字符串的解析:

方案1:使用Date构造函数的参数形式(最推荐)

直接传入年、月(注意月份从0开始,12月对应11)、日、时、分、秒,这种方式所有浏览器都能正确解析:

<script>
// Set the date we're counting down to - 2019年12月9日00:00:00 GMT-0500
var countDownDate = new Date(2019, 11, 9, 0, 0, 0).getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  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);

  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + " days remaining";

  // If the count down is over, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

方案2:使用ISO 8601标准格式

把日期字符串改成YYYY-MM-DDTHH:mm:ss±HH:mm的标准格式,同样能被所有浏览器正确解析:

var countDownDate = new Date("2019-12-09T00:00:00-05:00").getTime();

验证要点

修复后,你可以在移动端测试:countDownDate会正确返回时间戳,不再是NaN,后续的distance计算也能正常进行,倒计时就会显示正确数值了。

内容的提问来源于stack exchange,提问作者Ruben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:46:07