In this tutorial, you will learn how to calculate difference time between two dates in CSharp. The result difference will be listed in exactly date difference and total difference in days, hours, minutes and seconds.
DateTime startTime = Convert.ToDateTime("12 Aug 2012 12:30 PM"); DateTime endTime = Convert.ToDateTime("12 Sep 2012 15:30 PM"); //We subtract the time. TimeSpan span = endTime.Subtract(startTime); //This will just return the difference selected option Response.Write("Time Difference (seconds): " + span.Seconds + Environment.NewLine); Response.Write("Time Difference (minutes): " + span.Minutes + Environment.NewLine); Response.Write("Time Difference (hours): " + span.Hours + Environment.NewLine); Response.Write("Time Difference (days): " + span.Days + Environment.NewLine); //This will return the total difference based on selected options Response.Write("Total milliseconds: " + Math.Round(span.TotalSeconds, 2).ToString() + Environment.NewLine); Response.Write("Total Minutes: " + Math.Round(span.TotalMinutes,2).ToString() + Environment.NewLine); Response.Write("Total hours: " + Math.Round(span.TotalHours,2).ToString() + Environment.NewLine); Response.Write("Total days: " + Math.Round(span.TotalDays,2).ToString() + Environment.NewLine);