Tuesday 23 July 2019

How to a find date differences between two dates using c# datetime and timespan?

Hi Readers,

In this article, You will learn how to find a differences between two dates using c# datetime and timespan.

Scenario: Manger asked you to show how much time taken to finish the whole process of the application and here in application has 5 pages to process.

For this requirement, we are going to use Datetime and TimeSpan classes.

To simplify this scenario, Showing here with for loop,

Program.cs

using System;
using System.Threading;

namespace ConsoleAppNew
{
    class Program
    {
        static void Main(string[] args)
        {
         
           // Hold the startTime
            var startTime = DateTime.Now;

            // For 5 pages i am using for loop
            for(int index = 0; index <5;index++)
            {         
            // To differentiate the time, here used Sleep method.
            Thread.Sleep(1000);

            // Gets only time duration
            TimeSpan timeSpan = DateTime.Now.Subtract(startTime).Duration();

            // To see the timespan in terms of hours, minutes and seconds.
            Console.WriteLine(" Time taken to process the current page " + index + " is " + timeSpan.Hours +" hours "+ timeSpan.Minutes +" minutes "+ timeSpan.Seconds + " seconds.");
            }

    }
      }
}


Output for this program is:

 Time taken to process the current page 0 is 0 hours 0 minutes 1 seconds.
 Time taken to process the current page 1 is 0 hours 0 minutes 2 seconds.
 Time taken to process the current page 2 is 0 hours 0 minutes 3 seconds.
 Time taken to process the current page 3 is 0 hours 0 minutes 4 seconds.

 Time taken to process the current page 4 is 0 hours 0 minutes 5 seconds.

Hoping this article gives you a clear understaing on how to use datetime and timespan to get the required time in terms of hours, minutes and seconds.

Happy Coding : )

No comments:

Post a Comment