2014-12-13 119 views
-2

我在我的winform中有2个dateTimePicker。第一个dateTimePickers用于开始日期,另一个用于结束日期,现在我只想从那些dateTimePickers输入开始日期@结束日期,并且我自动在文本框中获得持续时间。如何计算持续时间?

回答

4

您可以通过减去两个日期计算的持续时间(这是在.NET称为TimeSpan):

TimeSpan ts = dateTimePicker2.Value - dateTimePicker1.Value; 

你可以得到秒的总金额,例如像这样:

double seconds = ts.TotalSeconds; 

设置一个像这样的文本框(您必须挂接任何事件才能触发此操作,例如DateTimePicker中的ValueChanged):

textBox1.Text = seconds.ToString("N0"); 
0

可以使用whuch返回一个时间跨度,然后使用时间跨度类方法

好运

0

这是一个办法做到这一点结果转换为日或一个月或一年的DateTime减去方法:

public partial class CalculateDuration : Form 
{ 
    public CalculateDuration() 
    { 
     InitializeComponent(); 


    } 

    //Computes the duration in days 
    private void Duration() 
    { 

     if (this.dateTimePicker1.Value.Day > this.dateTimePicker2.Value.Day) 
     { 
      if (this.dateTimePicker1.Value.Month == this.dateTimePicker2.Value.Month) 
      { 
       this.durationTextBox.Text = (-(this.dateTimePicker1.Value.Day - this.dateTimePicker2.Value.Day)).ToString(); 
      } 
      else 
      { 
       this.durationTextBox.Text = (this.dateTimePicker1.Value.Day - this.dateTimePicker2.Value.Day).ToString(); 
      } 

     } 
     else 
     { 
      this.durationTextBox.Text = (this.dateTimePicker2.Value.Day - this.dateTimePicker1.Value.Day).ToString(); 
     } 
    } 

    //This events is trigered when the value of datetimepicker is changed 
    private void dateTimePicker1_ValueChanged(object sender, EventArgs e) 
    { 
     Duration(); 
    } 

    private void dateTimePicker2_ValueChanged(object sender, EventArgs e) 
    { 
     Duration(); 
    } 
}