Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 2 DateTimes in Hours? [duplicate]

Tags:

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

like image 983
PassionateDeveloper Avatar asked Mar 03 '11 09:03

PassionateDeveloper


People also ask

How can you find the difference in time between two DateTime objects time_1 and time_2?

Just subtract one from the other. You get a timedelta object with the difference. Save this answer.

How do you find the difference between two dates in hours and minutes?

get time() -startDate. gettime())/1000; Log. d("App","difference in hour is"+diff/1000/60/60); Mins = diff/1000/60; Seconds = diff/1000; Using this code I'm getting hours as a correct value.


2 Answers

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.

like image 115
Jon Skeet Avatar answered Oct 04 '22 23:10

Jon Skeet


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

like image 26
Øyvind Bråthen Avatar answered Oct 04 '22 23:10

Øyvind Bråthen