我正在做一个必须使用 Javascript 的任务。在我的应用程序中,用户在表单中键入日期。然后我尝试将该日期与当前日期进行比较。不同之处在于他们必须完成一项任务的天数。但是,在计算方面我遇到了一些麻烦。dueDate 是动态创建的对象的参数。
function getFormData() {
var adate = document.getElementById("dueDate").value;
if (checkInputText(dueDate, "Please enter a date")) return;
...
}
function processDate(adate) {
var splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
var date = new Date(year, month, day);
var dateParse = date.getTime();
return dateParse;
}
function compareDates(dueDate) { //dueDate is the value from the form
var cdate = new Date();
console.log("this is todays date" + " " + cdate); //shows correct date
var cdateparse = Date.parse(cdate);
var dueDateparse = Date.parse(dueDate);
var diff = dueDateparse - cdateparse;
var daysCal = diff / 1000 / 60 / 60 / 24;
var days = parseInt(daysCal); //where I'm having trouble
console.log(days);
if (days == 0) {
mymessage = " you have to do this task today";
}
try {
if (days < 0) {
mymessage = "this task is overdue by" + " " + -days + " " + "days";
throw new Error("you are overdue");
}
} catch (ex) {
alert(ex.message);
return;
}
if (days > 0) {
console.log("the difference is greater than 0");
mymessage = "you have" + " " + days + " " + "more days";
}
}
当我将当前日期输入表格时,就会出现问题。我试过 math.floor 和 math.round 但这个数字总是四舍五入并抛出我的信息,说任务过期了。使用 parseInt 使我最接近我想要的结果,但是当我输入明天的日期时,它说我已经过期了。有什么建议么?