如何计算持续时间?

时间:2014-12-13 12:08:44

标签: c# .net

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

3 个答案:

答案 0 :(得分:4)

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

TimeSpan ts = dateTimePicker2.Value - dateTimePicker1.Value;

您可以获得总秒数,例如:

double seconds = ts.TotalSeconds;

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

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

答案 1 :(得分:0)

您可以使用DateTime Subtract方法返回TimeSpan,然后使用TimeSpan类方法将Result转换为Day或Month或year

祝你好运

答案 2 :(得分:0)

这是一种方法:

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();
    }
}