我试图让计时器倒数到几天的日期,我不知道为什么这不起作用它只是说NaN
function daysUntil24thApril2016() {
var april2016 = new Date(24, 4, 2016);
var difference = april2016.getMilliseconds - Date.now().getMilliseconds;
return difference / 1000 / 60 / 60 / 24;
}
$(document).ready(function() {
console.log("asdasd")
$('#dateTime').text(daysUntil24thApril2016());
});

答案 0 :(得分:3)
您在脚本中犯了几个错误,我会尝试解释每个错误以帮助您理解它,最后按照您编写的方式为您提供更正的脚本:
new Date()
首先需要year
,然后是month - 1
,最后是日期。因此,要获得2016年4月24日,您必须new Date(2016, 3, 24)
Date
,有getMilliseconds
函数,但它返回该日期的毫秒部分,而不是您想要的unix时间戳.getTime()
是从此日期开始以毫秒为单位获取unix时间戳的函数Date.now()
已经返回了unix时间戳(一个数字),没有getMilliseconds()
,因此返回undefined
getMilliseconds
函数,你在没有大括号()
的情况下编写它的方式也不会调用它但是返回了函数。他们编写它的方式导致var difference = function - undefined
导致NaN
:“不是数字”。difference
在您的示例中没有数字(它是Nan
)并且您无法使用它进行任何数学计算,它会保持NaN
Math.floor
将为您提供完整的日期请参阅下文,了解更正上述各点的脚本版本。
function daysUntil24thApril2016() {
var april2016 = new Date(2016, 3, 24);
var difference = april2016.getTime() - Date.now();
return Math.floor(difference / 1000 / 60 / 60 / 24);
}
$(document).ready(function() {
$('#dateTime').text(daysUntil24thApril2016());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dateTime"></div>
答案 1 :(得分:0)
这样的事情可以解决你的问题:
function daysUntil24thApril2016() {
var april2016 = new Date("2015-04-24");
var difference = Date.now()-april2016;
return Math.floor((difference) / (1000*60*60*24))
}
$(document).ready(function() {
console.log(daysUntil24thApril2016());
});
当您从另一个{1}}中减去一个Date
个对象时,您将获得以毫秒为单位的时差。使用Math.floor()
将返回整数(整数)天数。