嗨,这似乎很简单,但它不起作用!我试图获取两个大纪元数字,并在当天的循环中计算一周中的某一天。我需要这个,因为我想不计算周末的日子(即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
为什么我总是得到&#39; 6&#39;每个时代?我的Epoch价值观有问题吗?请注意,它是5天,所以每天长86400。
我将代码复制到此页面进行测试: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_getday
答案 0 :(得分:2)
在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>")
}
}
&#13;