IMG-LOGO

How to calculate difference time between two dates in ASP.Net C#?

andy - 20 Jul, 2013 7575 Views 1 Comment

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);

Comments

chris maria
04 Apr, 2017
its working....thank you
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.