How to find time difference between two time using c#.net?

By | September 17, 2014

In this article you will get the code for calculating time difference between two time using c#.Net. Suppose we have to calculate work hour of an employee for a particular date. Suppose his office in-time is “09:00AM” and out-time is “06:00PM”, then how to calculate the work hour or time difference? You can use Duration() method of TimeSpan to calculate absolute value of time difference.

Follow the below code to get the time difference:

DateTime dt1 = new DateTime();
dt1 = Convert.ToDateTime("09:00AM"); 
DateTime dt2 = new DateTime();
dt2 = Convert.ToDateTime("06:00PM");
TimeSpan ts = dt1.Subtract(dt2).Duration();

Hope this will help you to find the time difference.

Thank you.

gasprijs