How to find date difference in C#

A date and time format string is used in C# to define the specific textual representation of a DateTime value obtained through a formatting operation. This can be achieved by utilizing various overloads of the DateTime constructor, which enable the specification of individual components such as year, month, or day.

DateTime newDate = new DateTime(2000, 5, 1);

Here newDate represents year as 2000 and month as May and date as 1 .

Date difference in C#

When performing calculations with a DateTime structure in C#, such as adding or subtracting time, the original value of the structure remains unchanged. Instead, these calculations return a new DateTime structure that represents the result of the operation. To determine the difference between two DateTime instances, the DateTime.Subtract method can be used. It allows for calculating the time span between two dates or times.

System.TimeSpan diff = secondDate.Subtract(firstDate);

You can also find the difference between two dates using the following method.

String diff2 = (secondDate - firstDate).TotalDays.ToString();

Full Source C#
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { System.DateTime firstDate = new System.DateTime(2000, 01, 01); System.DateTime secondDate = new System.DateTime(2000, 05, 31); System.TimeSpan diff = secondDate.Subtract(firstDate); System.TimeSpan diff1 = secondDate - firstDate; String diff2 = (secondDate - firstDate).TotalDays.ToString(); MessageBox.Show(diff1.ToString ()); } } }