Calculating the Number of Years Interval Between Two Dates Using C#

In this tutorial, I will teach you how to calculate the number of years interval between two dates using C#. This simple program is commonly used for getting the age of the person or getting if how many years you have been working in a company. Follow the procedure below to see how it works

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create new windows for application for C#. datesinterval1

Step 2

Do the form just like this. datediff21

Step 3

Go to the code editor and create a function to get the number of years interval between two dates.
  1. private static int calculateYears(DateTime datefrom, DateTime dateto)
  2. {
  3. int int_year;
  4. int_year = dateto.Year - datefrom.Year;
  5. return int_year;
  6.  
  7. }

Step 4

Double click the button and do the following codes for getting the number of years interval between two dates and display it inside the listbox when the button is clicked.
  1.  
  2. private void button1_Click(object sender, EventArgs e)
  3. {
  4. listBox1.Items .Clear();
  5. int result_year = calculateYears(dateTimePicker1.Value, dateTimePicker2.Value);
  6. listBox1.Items.Add("Result :" + result_year + " Year(s)");
  7. }
For more question about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT FB Account – https://www.facebook.com/onnaj.soicalap Or feel free to comment below.

Add new comment