Friday, May 4

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
Post a Comment