How to Get the Hours Interval of Two Given Time in C#

In this tutorial, I will teach you how to get the hours interval of two given time in c#. This method has the ability to get the difference between two given time. It generates if how many hour intervals in the two given time that will be displayed inside the listbox. Let's begin.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Do the form just like shown below. ps2

Step 3

Press F7 to open the code editor and create a method for getting the hour interval between two given time.
  1.  
  2.         private void get_hours(TimeSpan ts,ListBox lst)
  3.         {
  4.             try
  5.             {
  6.                 lst.Items.Clear();
  7.                 lst.Items.Add(ts.Hours.ToString());
  8.  
  9.             }catch(Exception ex)
  10.             {
  11.                 MessageBox.Show(ex.Message);
  12.             }
  13.         }
  14.        

Step 4

Write the following codes to get the hours interval when the button is clicked.
  1.  
  2.         private void button1_Click(object sender, EventArgs e)
  3.         {
  4.             TimeSpan ts;
  5.             DateTime date_from,date_to;
  6.  
  7.             date_from = DateTime.Parse (dtp_From .Text );
  8.             date_to = DateTime.Parse(dtp_To .Text);
  9.             ts = date_to.Subtract(date_from);
  10.  
  11.             get_hours(ts, listBox1);
  12.  
  13.         }
  14.        
For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment