减去两个datetime变量

问题描述:

如何获取两个日期时间变量之间的总小时数?

How can i get total number of hours between two datetime variable?

date1=1/1/2011 12:00:00

date2=1/3/2011 13:00:00
datetime date1 ;

datetime date2;

int hours=(date1.date2).hours;

输出为"1",但我希望两个日期之间的总时差为49小时

the output is "1" but i want the total hour difference between two date i.e 49hours

谢谢

使用 小时 .请注意,结果是一个 double -您可以将其强制转换为 int 以获得整个小时数.(不过,如果结果为负,请检查您想要什么样的行为...)

Use TotalHours instead of Hours. Note that the result is a double - you can just cast it to int to get the whole number of hours. (Check what behaviour you want if the result is negative though...)

从文档中获取小时:

属性值:当前TimeSpan结构的小时部分.返回值的范围是-23到23

Property Value: The hour component of the current TimeSpan structure. The return value ranges from -23 through 23

您不需要小时 -您需要整个时间段,以小时为单位.

You don't want the hour component - you want the whole time span, expressed in hours.