开发者

subtracting two datetime variable

开发者 https://www.devze.com 2023-03-15 13:33 出处:网络
How can i g开发者_如何学运维et total number of hours between two datetime variable? date1=1/1/2011 12:00:00

How can i g开发者_如何学运维et 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;

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

thanks


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

From the docs for Hours:

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.


int hours = (int) (date2 - date1).TotalHours;


        DateTime date1 = new DateTime(2011, 1, 1, 12, 0, 0);
        DateTime date2 = new DateTime(2011, 1, 3, 13, 0, 0);
        TimeSpan ts = date2 - date1;

        double hours = ts.TotalHours;
0

精彩评论

暂无评论...
验证码 换一张
取 消