表单一个录入一个有效日期后,将日期和当前系统日期对比,如果在半年以内的,就提示用户有效期无效。我用的是:<input name="d1" type="text" onblur="chkdate(this.value)" />
function DateDiff(sDate){
  var aDate, oDate1, oDate2, iDays
  var a=new Date();
  var sDate1=a.getFullYear()+"-"+(a.getMonth()+1)+"-"+a.getDate()
  aDate = sDate1.split("-")   
  oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])   
  aDate = sDate.split("-")   
  oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])   
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24) 
  return iDays   

function chkdate(str){
alert(DateDiff(str));
if(DateDiff(str)<182){//问题就是这个半年的有效期怎么算啊?182天作半年也不对
  alert("对不起,请检查有效期是否在半年以内!");
}
} 半年应该用多少表示合适呢?也就是说录入的日期和当前系统日期的差值正好半年这种

解决方案 »

  1.   


    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script type="text/javascript">
    function chkdate(val){
    val = val.replace(/[-.]/g, "/");
    var y = new Date().getFullYear(),
    hy  = (new Date(y, 0, 1) - new Date(y - 1, 0, 1)) / 2,
    now = new Date().getTime(),
    chk = new Date(val).getTime();

    if(now - chk < hy){
    alert("对不起,请检查有效期是否在半年以内!");
    }
    };
    </script>
    </head>
    <body>
    <input name="d1" type="text" onblur="chkdate(this.value)" />
    </body>
    </html>
      

  2.   

    首先年相减,如果大于1提醒,不大于1,月相减大于6提醒,不大于6日相减得到的日加上每个月的日不就可以了?不过要考虑闰年。月的时间有30和31天的,写一个类来封装起来就好了
    var moth1 ={moth:"1",day:"31"} 
    var moth2 ={moth:"2",day:"28"} 
    .....
      

  3.   

    改了下。
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script type="text/javascript">
    function chkdate(val){
        val = val.replace(/[-.]/g, "/");
        var y    = new Date().getFullYear(),
            hy     = (new Date(y, 0, 1) - new Date(y - 1, 0, 1)) / 2,
            now = new Date().getTime(),
            chk = new Date(val).getTime();
            
        if(Math.abs(chk - now) < hy){
            alert("对不起,请检查有效期是否在半年以内!");
        }
    };
    </script>
    </head>
    <body>
    <input name="d1" type="text" onblur="chkdate(this.value)" />
    </body>
    </html>