0

我正在开发一个应用程序,我需要找到用户输入表单的日期与当前日期之间的差异。现在使用我拥有的代码,当我输入当前日期时,它总是显示差异 2。我将不胜感激任何关于如何解决这个问题的建议。

function compareDates(dueDate) {  //dueDate is the value from the form
var cdate = new Date();
var cdateparse = Date.parse(cdate);
var dueDateparse = Date.parse(dueDate);
var diff = dueDateparse - cdateparse;
var daysCal = diff / 1000 / 60 / 60 / 24;
var days = Math.floor(daysCal);
console.log(days);  //keeps returning -2 when I enter the current date into the form
try {
 if(diff < 0) {
 mymessage = "this task is overdue by" + " " + -days + " " + "days"; //shows 2 
  throw new Error("you are overdue");
  }
  }
 catch(ex) {
 alert(ex.message);
 return;
 }
if(diff > 0) {
console.log("the difference is greater than 0");
mymessage = "you have" + " " + days + " " + "more days";
}
}
4

3 回答 3

0

在应用 Math.floor() 之前,您必须对 daysCal 值进行四舍五入。

.....

var days = Math.floor(Math.round(daysCal));
.....
于 2013-03-19T04:34:49.067 回答
0

我会使用moment.js库来为你处理它,它有一个内置的不同API,并且可以像这样使用:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
于 2013-03-19T02:09:18.823 回答
0

首先获取您应该使用的当前日期,Date.now()而不是+new Date. 它在支持浏览器方面速度更快,而且这个 IE<9 的 polyfill很简单:

Date.now = Date.now || function() {
    return +new Date;
};

如果你使用moment.js,你甚至不需要这样做:

moment(someDate).fromNow()

.fromNow()在 momentjs.com 上


我会推荐使用 moment.js 作为@Slace 推荐的。我正在制作的网络应用程序中使用 moment.js。他们的相对日期方法返回易于阅读的格式,如“几秒钟前”、“四年前”等。超级简单!

于 2013-03-19T04:47:36.537 回答