如何在文本框中找到两个日期之间的差异?

时间:2012-04-18 09:07:40

标签: javascript asp.net

我想找到两个日期之间的差异,其中m在文本框中给出日期值,我想要差异/持续时间到其他一些文本框。

 <script language=javascript>
        function formshowhide(id) {
      if (id == "other") {
          //document.getElementById('quotef').style.display = "block";
          document.getElementById('otherf').style.display = "block";

     //here m writng the function for finding duration
          var txtdate1 = document.getElementById('MainContent_txtOStartDate').value;
          var txtdate2 = document.getElementById('MainContent_txtOEndDate').value;
          var date1 = new Date(txtdate1.split('-')[0], txtdate1.split('-')[1] - 1, txtdate1.split('-')[2]);
          var date2 = new Date(txtdate2.split('-')[0], txtdate2.split('-')[1] - 1, txtdate2.split('-')[2]);
          var timediffsec = date2.getTime() - date1.getTime();
          var timediffday = parseInt(timediffsec / (24 * 3600 * 1000));
          document.getElementById('MainContent_txtDays').value = timediffday;
     //here the function end for finding the duration
      }
      else {
          // document.getElementById('quotef').style.display = "none";
          document.getElementById('otherf').style.display = "none";
      }
  }
  </script>

1 个答案:

答案 0 :(得分:1)

// Assuming you already have validation on the date input text boxes
DateTime startDate = Convert.ToDateTime(txtOStartDate.Text);
DateTime endDate = Convert.ToDateTime(txtOEndDate.Text);
TimeSpan timeDiff = startDate - endDate;

然后你可以从时间跨度中显示你想要的任何东西:

string.Format("{0} days, {1} hours and {2} minutes.", timeDiff.Days, timeDiff.Hours, timeDiff.Minutes);