Quick Tip–How to get time difference in C#

Recently, One of the reader of this asked me about, how we can get time difference between two dates or two times? So I thought it will be a good idea to write a blog post about that. So that other use can also get benefit from that.

For that I have created sample console application like below.
using System;

namespace TimeDifferenceCSharp
    class Program
        static void Main(string[] args)
            DateTime firstDate = DateTime.Parse("12:50");
            DateTime secondDate = DateTime.Parse("10:40");

            TimeSpan difference = TimeSpan.Parse(firstDate.Subtract(secondDate).ToString());

In above example, If you see it carefully I have taken two dates with different time. Then I have used subtract method DateTime class to find different of both and then I parse it to TimeSpan class. After that I have printed hours and minutes for  via Console.Writeline method.

Now let’s run this application. You will see output as following.


That’s it.Hope you like it.

You can find complete source code of this blog post at github on- https://github.com/dotnetjalps/TimeDifferenceInCSharp


Popular posts from this blog

Creating PDF with ASP.Net MVC and RazorPDF

Horizontal and vertical scrollbar in HTML5 and CSS3

How to create Rest API(Web API) with ASP.NET Core 1.0