saurabh goyal
saurabh goyal

Reputation: 1744

subtracting two datetime variable

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;

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

thanks

Upvotes: 0

Views: 1964

Answers (3)

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

        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;

Upvotes: 3

agent-j
agent-j

Reputation: 27953

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1504072

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.

Upvotes: 9

Related Questions