Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get difference of dates

Tags:

c#

datetime

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;
like image 458
David Filo Avatar asked Dec 09 '22 21:12

David Filo


2 Answers

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

TimeSpan span = date1.Subtract(date2);
long hours = (long)span.TotalHours;
like image 160
saj Avatar answered Dec 11 '22 10:12

saj


var hours = (date1 - date2).TotalHours;

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

var hours = Math.Floor((date1 - date2).TotalHours);
like image 42
Justin Niessner Avatar answered Dec 11 '22 09:12

Justin Niessner