2014-12-13 118 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(); 
    } 
}