<input type="text" id="d1"/> <input type="text" id="d2" nblur="compare()"/> <script> function compare() { var d1 = document.getElementById("d1").value; var d2 = document.getElementById("d2").value; arr1 = d1.split("-"); arr2 = d2.split("-"); date1 = new Date(arr1[0],arr1[1],arr1[2]); date2 = new Date(arr2[0],arr2[1],arr2[2]); if(date2.getTime()<date1.getTime()) { alert("不能比第一个日期小"); return false; } } </script>
第二种
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> < % String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html> <head> <base href="<%=basePath%>"> <title>判断第二个日期比第一个日期大</title> <script type="text/javascript"> window.onload = function() { //这么写是为了实现js代码与html代码的分离,当我修改js时,不能影响html代码。 document.getElementByIdx_x("frm1").onsubmit = function(){ var d1 = this.d1.value; var d2 = this.d2.value; if(!verifyDate (d1)) {alert("第一个日期格式不对");return false;} if(!verifyDate (d2)) {alert("第二个日期格式不对");return false;} if(!compareDate(d1,d2)) {alert("第二个日期比第一日期小");return false;} }; } function compareDate(d1,d2) { var arrayD1 = d1.split("-"); var date1 = new Date(arrayD1[0],arrayD1[1],arrayD1[2]); var arrayD2 = d2.split("-"); var date2 = new Date(arrayD2[0],arrayD2[1],arrayD2[2]); if(date1 > date2) return false; return true; } function verifyDate(d) { var datePattern = /^d{4}-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2]d|3[0-1])$/; return datePattern.test(d); } < /script> </head> <body> <form id="frm1" action="xxx.html"> <input type="text" name="d1" /> <input type="text" name="d2" /> <input type="submit" /> </form> </body> < /html>