4

I was wondering how I can get the difference between two dates in complete hours

e.g.

DateTime date1 = DateTime.Now;
DateTime date2 = new DateTime(2011, 8, 5, 33,00); 
long hours = date1 - date2;
David Filo
  • 55
  • 4

5 Answers5

5

It's the cast to long/int that will give you complete hours.

TimeSpan span = date1.Subtract(date2);
long hours = (long)span.TotalHours;
saj
  • 4,626
  • 2
  • 26
  • 25
4
var hours = (date1 - date2).TotalHours;

Or, if you don't want the fraction of an hour:

var hours = Math.Floor((date1 - date2).TotalHours);
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • @saj - What do you consider "complete hours" then? And, by the way, the result of this statement is the exact same as yours (date subtraction in this form results in a TimeSpan as well). – Justin Niessner Aug 30 '12 at 14:52
  • A full 60 mins, total hours returns a double I would expect no decimals – saj Aug 30 '12 at 14:53
3

You can use the TimeSpan by subtracting both dates:

DateTime date1 = DateTime.Now;
DateTime date2 = new DateTime(2011, 8, 5); 
TimeSpan ts = date1 - date2;
long hours = (long)ts.TotalHours;

If you want to round it as accurate as possible, you can use Math.Round:

long hours = (long)Math.Round(ts.TotalHours, MidpointRounding.AwayFromZero);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You can try with

  var result = date1 - date2;
    var hours = result .TotalHours;
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
1

I've found a very nice DateTimeSpan implementation that I use to calculate various differences, hours, days, months in this post

Community
  • 1
  • 1
Marty
  • 3,485
  • 8
  • 38
  • 69