Skip to main content

Date difference in C#

We have to create an object of the TimeSpan Class to get difference between two dates or time.
Then use the Subtract method of TimeSpan Class to get the difference.

You can use Days, Hours, Minutes and Seconds property of the TimeSpan Class to get flexible results.

 // current date time
 DateTime d1 = DateTime.Now;
 
    // or can get date from DB by converting it into datetime 
 DateTime d2 = new DateTime(2004, 06, 16); 
  
 //create a timespan object to get the difference between dates ( d1 - d2 ) 
 TimeSpan ts = d1.Subtract(d2);
 
 //Timespan has days, hours, years, seconds, minutes etc which can be used as below
 int hours = (ts.Days * 24) + ts.Hours; 
  

some Reference Links are here if you could not understand my grammer
  1. http://stackoverflow.com/questions/4946316/showing-difference-between-two-datetime-values-in-hours
  2. http://www.dotnetspider.com/forum/539-Date-Difference-C.aspx
  3. http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx

Comments

Popular posts from this blog