Reputation: 55
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
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
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
Reputation: 29000
You can try with
var result = date1 - date2;
var hours = result .TotalHours;
Upvotes: 1
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
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