Difference between two Dates in C#.NET ?

To find the difference between two dates is very simple in VB — By using DateDiff method. But in C#, there is no direct method to do so. but there is a way to achive this. For this we need to understand TimeSpan Class.

The following code snippet will show you how to find the difference.

DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( “Time Difference (seconds): ” + span.Seconds );
Console.WriteLine( “Time Difference (minutes): ” + span.Minutes );
Console.WriteLine( “Time Difference (hours): ” + span.Hours );
Console.WriteLine( “Time Difference (days): ” + span.Days );

By concatenating all this you will get the difference between two dates. You can also use span.Duration().

There are certain limitations to. The TimeSpan is capable of returning difference interms of Days, Hours, mins and seconds only. It is not having a property to show difference interms of Months and years.

Hope this will help you… 

Advertisements

First make your habits and then your habits make U!!!

PLAN while others are Playing.
STUDY  while others are Sleeping.
DECIDE while others are Delaying.
PREPARE while others are Daydreaming.
BEGIN while others are Procrastinating.
WORK  while others are Wishing.
SAVE while others are Wasting.
LISTEN while others are Talking.
SMILE while others are Frowning.
COMMEND while others are Criticizing.
PERSIST while others are Quitting.