From JavaScript, how do you compare two text fields containing date strings for order, to see which one comes first?

Jayesh Nazre

Use the value returned from the Date.parse() method and compare like numbers.

<html>
<head>
<script language=javascript>
function compareDate() {

var d1 = 
  Date.parse(document.frm_date.txt_dt1.value);
var d2 = 
  Date.parse(document.frm_date.txt_dt2.value);

if (d1 < d2) {
  alert ("Date 1 is Less than Date 2");
} else if (d1 > d2) {
  alert ("Date 1 is Greater than Date 2");
} else {
  alert ("The two dates are same");
}


}
</script>
</head>
<body>
<form id=frm_date name=frm_date>
Date 1
<input 
  type=text 
  value="01/02/2000" 
  id=txt_dt1 
  name=txt_dt1>
Date 2
<input 
  type=text 
  value="02/02/2000" 
  id=txt_dt2 
  name=txt_dt2>

<input type=button value=Compare 
  onclick=compareDate()>
</form>
</body>
</html>
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact