当前位置 : 首页 » 编程语言 » 正文

js时间比较示例分享(日期比较)

分类 : 编程语言 | 发布时间 : 2018-04-21 09:06:21 | 浏览 : 0

复制代码 代码如下:

<html>
 <head>
  <script language="javascript" type="text/javascript">
   /** 日期比较 **/
   function compareDate(strDate1,strDate2)
   {
    var date1 = new Date(strDate1.replace(/\-/g, "\/"));
    var date2 = new Date(strDate2.replace(/\-/g, "\/"));
    return date1-date2;
   }

   /** 比较 **/
   function doCompare(){
    var strDate1 = document.getElementById("strDate1").value;
    var strDate2 = document.getElementById("strDate2").value;
    var result = compareDate(strDate1,strDate2);
    if ( result>0 ) {
     alert("strDate1晚于strDate2");
    }else if( result<0 ){
     alert("strDate1早于strDate2");
    }else if ( result==0 ){
     alert("strDate1等于strDate2");
    }
   }
  </script>
 </head>
 <body>
  <input type="text" id="strDate1" name="strDate1" value="2012-07-01"/>
  <input type="text" id="strDate2" name="strDate2" value="2012-08-01"/>
  <input type="button" id="compareBtn" name="compareBtn" value="比较" onClick="doCompare();"/>
 </body>
</html>

相关阅读:

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery

Resize HTML5 canvas to fit window

How do I replace a character at a particular index in JavaScript?

JavaScript file upload size validation

Converting a string to a date in JavaScript

How to get the data-id attribute?