Comparing Two Dates in Select Box - Problem Solved
Hi, Please help me I am new at javascript.
The problem:
Compare and validate between two dates in a select field where End Date should always be greater than Start Date.
For example
1. Start Date 26/09/2003 when compare with End Date 26/07/2003 should return an error.
Note: The Start Date could be any future Date. The requirement is that Start Date have to always be less than or
equal to End Date. Else return and error.
I have no problem validating the difference in year and date, but the month is not responding.
The following is the code.
checkForm.js
/*********************/
function compareTwoDate(startDate, endDate, startMonth, endMonth, startYear, endYear){
if (endYear.value >= startYear.value && endMonth.value < startMonth.value){
alert("Expiry Month must be greater than or equal to Start Month");
return false;
}
else if (endYear.value >= startYear.value && endMonth.value >= startMonth.value){
if (endDate.value < startDate.value){
alert ("Expiry Date must be greater than or equal to Start Date");
}
else
return true;
}
else
alert("Expiry Year must be greater than or equal to Start Year");
return true;
}
/*********************************/
The above function is called within the date.html via check_form()
date.html
/********************************/
<html>
<head></head><body>
<script language="JavaScript" src="checkForm.js"></script>
<script language="JavaScript">
function check_form()
{
var startdate = document.date_form.startdate ;
var startmonth = document.date_form.startmonth;
var startyear = document.date_form.startyear;
var endDate = document.date_form.endDate ;
var endMonth = document.date_form.endMonth;
var endYear = document.date_form.endYear;
ok = false;
ok = (compareTwoDate (startday, endDay, startmonth, endMonth, startyear, endYear));
Setting the field to current date is not a problem. It is done by this script
<script type="text/javascript" language="javascript">
function setDate() {
var today = new Date();
with (document.date_form) {
startmonth.selectedIndex = today.getMonth();
startdate.selectedIndex = today.getDate() - 1;
var thisyear = today.getYear().toString();
startyear.selectedIndex = thisyear.charAt(thisyear.length-1) - 2;
endMonth.selectedIndex = today.getMonth();
endDate.selectedIndex = today.getDate() - 1;
var thisyear = today.getYear().toString();
endYear.selectedIndex = thisyear.charAt(thisyear.length-1) - 2;
}
}
</script>
What I want is to compare the Start Month to End Month
where if Start Year is = to End Year than
Start Month have to be either = to less than End Month.
Bookmarks