我有一个要求,我需要找到在文本字段中输入的日期不应超过当前日期的1年。我已经为前一个编码,但对于后一个要求我不能这样做。
function validateNetworthDate() {
var netWorthFlag = $("#NetworthDate").val();
//netWorthFlag is coming( the date we entered) : "15/01/2015"
var errorMsg='';
var currentTime = new Date();
var currentDay = currentTime.getDate();
var currentMonth = currentTime.getMonth()+1; //As January is 0!
var currentYear = currentTime.getFullYear();
if(currentDay<10) {
currentDay='0'+currentDay
}
if(currentMonth<10) {
currentMonth='0'+currentMonth
}
var enteredDay=netWorthFlag.substr(0,2);
var enteredMonth=netWorthFlag.substr(3,2);
var enteredYear=netWorthFlag.substr(6,4);
var enteredDateFormat=enteredYear+'/'+enteredMonth+'/'+enteredDay;
//Now entered date should be : "2015/01/15"
var enDate = new Date(enteredDateFormat);
var compDate = currentTime - enDate;
if (compDate<0)
{
errorMsg="Future Date not allowed.";
}
//Can you please suggest that what should I write here to do validation that Date should not be older than 1 year from current date (Today's date)
}
答案 0 :(得分:0)
尝试这个,在从输入中获取字符串后,可以将函数调用为,
function dateDiff(entereddate) {
one_year_next_date = new Date(new Date().setYear(new Date().getFullYear() + 1))
entereddate = new Date(entereddate);
return (one_year_next_date.getTime() - entereddate.getTime()) / 1000 / 60 / 60 / 24 // diff in days
}
var netWorthFlag = $("#NetworthDate").val();
date_difference = dateDiff(netWorthFlag); /* your input entered date */
/* eg: dateDiff("02/16/2015"); */(check date format ("02/16/2015"))
这会将日期差异作为天数返回。
然后你可以写下你的病情,
if(date_difference > 365(/* 366 */))
/**** You can even check the leap year of entered date, or next years date ****/
{
/**** do your stuff ****/
}
else
{
/**** do your stuff ****/
}
你甚至可以在这里检查闰年,从该日期算起一年。(检查日期格式(“02/16/2015”))
答案 1 :(得分:0)
在这里查看:
https://jsfiddle.net/v63u7ksf/
var yearAgoTime = new Date().setFullYear(currentTime.getFullYear()-1);
var compDate2 = enDate - yearAgoTime;
if (compDate2<0)
{
errorMsg="More than 1 year ago not allowed.";
}
答案 2 :(得分:0)
您可以按照其他人的建议自行检查差异,但是,我建议您使用moment.js
进行日期时间处理。非常方便。