views:

1010

answers:

5

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);
+3  A: 

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.

JaredPar
Still wrong. TotalHours is a double, returning whole and fractional hours.
Vilx-
@Vilx, not necessarily wrong. The OP's intent is ambiguous
JaredPar
Its the right answer for the question, he wants the result to be 24 which it would be. Of course he could round the TotalHours himself quite easily if that is what he wants.
James Avery
@James my answer produces 24 exactly. The OP did not specify the value had to be a particular number format.
JaredPar
Whats OP.......?
abmv
@abmv: "OP" - Original Poster. In this case, you.
Cerebrus
@Jared, I know I was agreeing with you. I think your answer is the better answer than the chosen one.
James Avery
@James, sorry. Only halfway throught the first cup of coffee this morning and not completely awake. :)
JaredPar
A: 

Are you perhaps looking for:

int Difference = (a-b).Hours;
Vilx-
It gives me a return 1?
abmv
+15  A: 

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.

Joey Robert
TimeSpan span = x.ShiftEndTime.Subtract(x.ShiftStartTime)if (span.TotalHours == 24) {do...}
abmv
A: 
TimeSpan ts = b.Subtract(a);
int difference = (int)ts.TotalHours;
Damien
A: 
var theDiff24 = (b-a).Hours
diadiora