我有一个要求,我需要找到在文本字段中输入的日期不应小于当前日期,未来日期不应超过距离日期1年后的确切日期。我已经为前一个编码,但我后来要求我不能这样做。 我在这里发布了用于检查少于当前日期的代码。如果输入的日期超过1年后的日期,请告诉我。
var currentDate = new Date();
var nextDate = new Date();
function checkLessThanCurrentDate() {
//var dateEntered = arguments[0]; -->Will have date that come form textfield
var day = dateEntered.split("/")[0];
var month = dateEntered.split("/")[1];
var year = dateEntered.split("/")[2];
//--->Logic for chekcing date less than current date
if ((year < currentDate.getFullYear() || (month - 1 < currentDate.getMonth() &&
year <= currentDate.getFullYear()) || ((day < currentDate.getDate()) && (month -
1 <= currentDate.getMonth()) &&
(year <= currentDate.getFullYear())))) {
return true;
}
else {
return false;
}
}
答案 0 :(得分:1)
以下是如何从现在开始一年的日期:
var now = new Date();
var oneYear = new Date();
var oneYear.setYear(now.getFullYear() + 1);
if (dateEntered > oneYear) {
// logic
}
答案 1 :(得分:1)
我认为这应该适用于您的要求:
function isValidDate(dateToCheck)
{
return isLessThanYearFromToday(dateToCheck) && dateToCheck >= new Date();
}
function isLessThanYearFromToday(dateToCheck)
{
var yearFromToday = new Date();
yearFromToday.setFullYear(yearFromToday.Year + 1);
return dateToCheck <= yearFromToday;
}
答案 2 :(得分:0)
您需要使用.getTime()
方法。 .getTime() return the time in millisonds
var toDayDate = new Date();
var enteredDate = new Date('06/09/2015'); // mm/dd/yyyy formate
if(toDayDate.getTime()<enteredDate.getTime() && toDayDate.getTime()+(365*24*60*60*1000) > enteredDate.getTime()){
alert();
}
<强> DEMO 强>