Calculate difference between two dates from DateTimePicker using C# in Windows Forms Application

Last Reply on Feb 07, 2018 05:47 AM By dharmendr

Posted on Feb 06, 2018 05:23 AM

hi all, i have two textbox that contains datepickers, what i want is a code that can generate the two dates that i have picked from the datepickers and display the total days inside the third textbox


Posted on Feb 06, 2018 06:16 AM Modified on on Feb 06, 2018 10:24 PM

Hi lingtyson,

Check this example. Now please take its reference and correct your code.



private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    DateTime inTime = Convert.ToDateTime(dateTimePicker1.Text);
    DateTime outTime = Convert.ToDateTime(dateTimePicker2.Text);
    if (outTime >= inTime)
        textBox1.Text = outTime.Subtract(inTime).Days.ToString();


Private Sub dateTimePicker1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim inTime As DateTime = Convert.ToDateTime(dateTimePicker1.Text)
    Dim outTime As DateTime = Convert.ToDateTime(dateTimePicker2.Text)
    If outTime >= inTime Then
        textBox1.Text = outTime.Subtract(inTime).Days.ToString()
    End If
End Sub


Posted on Feb 07, 2018 05:47 AM

Already provided you the complete code. Please check does you have assigned event handler for both the DateTimePicker.

If you have not assigned the go to the property of DateTimePicker and assign ValueChanged event handler for these.

You can also assign using code behind. For this you need to add the below line of code.

public Form1()
    dateTimePicker1.ValueChanged += new EventHandler(dateTimePicker1_ValueChanged);
    dateTimePicker2.ValueChanged += new EventHandler(dateTimePicker1_ValueChanged);