我想计算今天和给定日期之间的天数,并检查截至今天剩余的天数或今天过去的天数.
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = today.getTime() - date_to_reply.getTime();
console.log( Math.floor(timeinmilisec / (1000 * 60 * 60 * 24)) );
Run Code Online (Sandbox Code Playgroud)
这给了我5个答案,但是我应该如何得到(-5),因为date_to_reply是从今天起的5天过去了?
这是计算任何给定日期的正确方法吗?
问候
小智 5
你正在做的是正确的:你想要计算两个日期之间的差异(以天数为单位).差异不能小于零.
虽然你date_to_reply已经过去了,但仍有5天的差异.
所以,一切都很好 - 这是正确的方法.
编辑:如果你想要一个负值作为结果,试试这个:
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = date_to_reply.getTime() - today.getTime();
console.log( Math.ceil(timeinmilisec / (1000 * 60 * 60 * 24)) );
Run Code Online (Sandbox Code Playgroud)
请记住,您需要Math.ceil获得最终结果,而不是将其四舍五入Math.floor().