javascript - Javascript 中 getDay 的问题

标签 javascript

嗨,这看起来很简单,但它不起作用!我正在尝试获取两个 Epoch 数字并计算当天循环中的星期几。我需要这个,因为我不想计算周末的天数(即 0 或 6)。

    <!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to display todays day of the week.</p>

    <button onclick="myFunction()">Try it</button>

    <p id="demo"></p>

    <script>
    function myFunction() {
    var oneDay = 86400;
    var days = 0;
    var currDay = 0;
    //var d = new Date();
    // get the start time in Epoch
    var dayTime = 1425531600 //from the user selection
    var endTime = 1425960000

    //while our dayTime is less than the end time,
    //loop through the days and count them.
    while (dayTime < endTime) {
        // advance one day
        dayTime = dayTime + oneDay;
        document.write("out:"+dayTime+"<br>")

        //turn the new time in Epoch into a date
        var d = new Date(dayTime);
        document.write("out:"+d.getDay()+"<br>")

    }

    }
    </script>

    </body>
    </html>

输出看起来像这样:

    out:1425618000
    out:6
    out:1425704400
    out:6
    out:1425790800
    out:6
    out:1425877200
    out:6
    out:1425963600
    out:6

为什么每个纪元我总是得到“6”?我的 Epoch 值有问题吗?请注意,它是 5 天,所以每天的长度为 86400。

我将代码复制到此页面中进行测试: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_getday

最佳答案

new Date(x) 中,x 需要采用 unixEpoch 格式 (毫秒) - 或 other formats .要解决您的问题,只需将所有值乘以 1000:

window.onload = function() {
  var oneDay = 86400000;
  var days = 0;
  var currDay = 0;
  //var d = new Date();
  // get the start time in Epoch
  var dayTime = 1425531600000 //from the user selection
  var endTime = 1425960000000

  //while our dayTime is less than the end time,
  //loop through the days and count them.
  while (dayTime < endTime) {
    // advance one day
    dayTime = dayTime + oneDay;
    document.body.insertAdjacentHTML('beforeend',"out:" + dayTime + "<br>")

    //turn the new time in Epoch into a date
    var d = new Date(dayTime);
    document.body.insertAdjacentHTML('beforeend',"out:" + d.getDay() + "<br>")

  }
}

关于javascript - Javascript 中 getDay 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28953243/

相关文章:

javascript - jQuery slideUp/Down 奇怪事件

javascript - 将 Promise 与 Mongoose 结合使用的最佳实践

javascript - 自动完成列表在 3 个字符后显示

javascript - js函数不改变值

javascript - 有没有办法在这个 v-for 中正确使用索引而不出现错误

javascript - Javascript 可以调用 Django 方法/函数吗?

javascript - 如何获取循环中给定值的总和?

javascript - 如何在单击图像时勾选复选框

javascript - 引用类对象属性

javascript - 如何使用javascript中的变量更改DIV的宽度和高度?