Tuesday, September 26, 2006

Javascript to compare dates

When I came across this scenario, I went through many sites for a solution. I came to notice one thing, which some of them have taken a long path to convert a string to a date object. This can be achieved through simple one line of code.

say,

form name - form ; field name - txtDate

date1 = new Date(form.txtDate1.value); //line to convert a string to a date

This simple javascript will convert the string to a Date.

To compare two dates we can simply write javascript as below.

if (date1 > date2) //where date2 is another date converted from a string

{
//Action
....
}

Below is a sample script.

<script language="javascript">
function check(form)
{
date1 = new Date(form.txtDate1.value);
date2 = new Date(form.txtDate2.value);

if(date2 < date1)
{
alert("Date Range Invalid");
form.txtDate2.focus();
return false;
}
}
</script>

No comments: