Difference between two DateTimes C#?

I need a function that can return the difference between the below two dates as 24.

DateTime a = new DateTime(2008, 01, 02, 06, 30, 00);
DateTime b = new DateTime(2008, 01, 03, 06, 30, 00);

Solution 1:

You can do the following:

TimeSpan duration = b - a;

There's plenty of built in methods in the timespan class to do what you need, i.e.

duration.TotalSeconds
duration.TotalMinutes

More info can be found here.

Solution 2:

Try the following

double hours = (b-a).TotalHours;

If you just want the hour difference excluding the difference in days you can use the following

int hours = (b-a).Hours;

The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case).

The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.

Solution 3:

Are you perhaps looking for:

int Difference = (a-b).Hours;