David Filo
David Filo

Reputation: 55

How to get difference of dates

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;

Upvotes: 4

Views: 129

Answers (5)

Marty
Marty

Reputation: 3555

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

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460268

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

Upvotes: 3

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You can try with

  var result = date1 - date2;
    var hours = result .TotalHours;

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245479

var hours = (date1 - date2).TotalHours;

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

var hours = Math.Floor((date1 - date2).TotalHours);

Upvotes: 4

saj
saj

Reputation: 4806

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

TimeSpan span = date1.Subtract(date2);
long hours = (long)span.TotalHours;

Upvotes: 5

Related Questions