Take the 2-minute tour ×

How do I find the time difference between two datetime objects in ASP.NET?

share|improve this question
add comment

7 Answers

up vote 40 down vote accepted

The following example demonstrates how to do this:

DateTime a = new DateTime(2010, 05, 12, 13, 15, 00);
DateTime b = new DateTime(2010, 05, 12, 13, 45, 00);

When executed this prints "30" since there is a 30 minute difference between the date/times.

The result of DateTime.Subtract(DateTime x) is a Timespan object which gives other useful properties.

share|improve this answer
You want TotalMinutes, not Minutes - the latter returns the minute component of the TimeSpan, e.g. 10 in 1:10:32 –  Ben M May 12 '10 at 17:13
this is what i want –  MarsMan May 12 '10 at 17:19
To display the difference, do something like this:Console.WriteLine((a - b).ToString(@"hh\:mm\:ss")). See: MSDN Custom TimeSpan Format –  ishmael Nov 5 '12 at 20:07
add comment

You want the TimeSpan struct:

TimeSpan diff = dateTime1 - dateTime2;


There are various methods for getting the days, hours, minutes, seconds and milliseconds back from this structure.

share|improve this answer
add comment

What you need is to use the DateTime classs Subtract method, which returns a TimeSpan.

var dateOne = DateTime.Now;
var dateTwo = DateTime.Now.AddMinutes(-5);
var diff = dateTwo.Subtract(dateOne);
var res = String.Format("{0}:{1}:{2}", diff.Hours,diff.Minutes,diff.Seconds));
share|improve this answer
add comment

The way I usually do it is subtracting the two DateTime and this gets me a TimeSpan that will tell me the diff.

Here's an example:

DateTime start = DateTime.Now;
// Do some work
TimeSpan timeDiff = DateTime.Now - start;
share|improve this answer
add comment

You need to use a TimeSpan. Here is some sample code:

TimeSpan sincelast = TimeSpan.FromTicks(DateTime.Now.Ticks - LastUpdate.Ticks);
share|improve this answer
Or just TimeSpan sincelast = DateTime.Now - LastUpdate; –  Ben M May 12 '10 at 17:17
Thanks for the tip. I had no idea you could do it that way. –  Jason Webb May 12 '10 at 18:06
add comment

IF they are both UTC date-time values you can do TimeSpan diff = dateTime1 - dateTime2;

Otherwise your chance of getting the correct answer in every single possible case is zero.

share|improve this answer
add comment
private void button1_Click(object sender, EventArgs e)
    TimeSpan timespan;
    timespan = dateTimePicker2.Value - dateTimePicker1.Value;
    int timeDifference = timespan.Days;
share|improve this answer
add comment

Your Answer


