我已經非常廣泛地研究了這個問題,並且我找到了一些有用的信息,但是我一直無法解決我的問題。我所要做的就是解析一個日期並將它與另一個日期進行比較。似乎很簡單,對吧?以下是我已經試過:爲什麼我的日期比較在JavaScript中不起作用?
function getCurrentDate() { //this function simply returns today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
return today;
}
$("#TxtDate").blur(function() {
var projectDueDate = Date.parse($("#lblDueDate").val()); //parses the project due date label to create a date variable
var itemDueDate = new Date($("#TxtDate").val()); //parses the value the user entered into the due date box to create a date variable
var actualProjectDueDate = new Date(projectDueDate);
if (Date.parse(document.getElementById('TxtDate').value) > getCurrentDate()) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtDate").val() = "";
}
});
的if
聲明未在TxtDate
blur
功能工作。它不顯示警報窗口,即使我輸入的日期早於今天的日期。正如你所看到的,我嘗試了一些不同的東西。有什麼建議麼?
在處理日期時,所有*看起來都很簡單。不是。使用庫 - http://momentjs.com – Jamiec
你正在比較一個日期到一個字符串... –
順便說一句,bith的答案是正確的,但就此而言,爲什麼要從'Date'轉到'string'並返回到'日期「 - 你已經知道如何獲得今天的日期作爲日期對象(你在'getCurrentDate'中做過) – Jamiec