22

Possible Duplicate:
Showing Difference between two datetime values in hours

Hi,

is there an easy way to get the difference between 2 DateTime-Values in Hours?

I know, its a possibility to calculate itself by get for each day difference 24h, for each month 188h and so on... but is there an easy way given mybe?

Example:

1) 01.02.2010 12:00
2) 03.03.2011 14:00

= ? Hours differnce

Community
  • 1
  • 1
PassionateDeveloper
  • 14,558
  • 34
  • 107
  • 176

5 Answers5

68

It's pretty simple:

TimeSpan diff = secondDate - firstDate;
double hours = diff.TotalHours;

Note that if these DateTime values have been taken locally, the results may not be the number of elapsed hours. For example, you could have one DateTime of midnight and one of 2am, but only one hour had elapsed - because the clocks went forward at 1am. This may or may not be an issue for you. It won't be a problem if you're dealing with UTC DateTime values.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
8

(dateTime1-dateTime2).TotalHours will give a double with the total difference in hours between the two.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
5
date1.Subtract(date2).TotalHours
Ed S.
  • 122,712
  • 22
  • 185
  • 265
1
TimeSpan difference = firstDateTime - secondDateTime;
double diffInHours = difference.TotalHours
Dave D
  • 8,472
  • 4
  • 33
  • 45
  • But i think its true that if " TimeSpan difference = secondDateTime -firstDateTime ;" ! – Ali Feb 04 '17 at 16:16
  • @combo_ci depends entirely on what you're trying to do. Neither firstDateTime nor secondDateTime dicated which was the earlier or later, nor whether diffInHours would be positive or negative, nor which was was required. It's a generic example of using TimeSpan arithmetic – Dave D Feb 05 '17 at 21:05
1

DateTime.Subtract(DateTime) will return a TimeSpan that has a TotalHours property.

Ian
  • 33,605
  • 26
  • 118
  • 198