Coder Perfect

Difference in hours between two datetime values


I’m looking for two date/time variables in the database. I need the difference between the two values once the value has been retrieved. To do so, I establish a timespan variable to hold the difference between the two dates.

TimeSpan? variable = datevalue1 - datevalue2;

Now I need to display the difference between the two values contained in the Timespan variable in terms of hours. I mentioned TimeSpan. TotalHours, but for some reason I was unable to apply the same. How can I go about doing that? On an MVC project, I’m using C#. I’m just looking for a way to represent the difference in hours.

I couldn’t utilize the total hours property since timespan was nullable. I can now utilize it by typing TimeSpanVal.Value.TotalHours into the console.

Asked by reggie

Solution #1

You might also take a peek at

var hours = (datevalue1 - datevalue2).TotalHours;

Answered by MarkKGreenway

Solution #2

I believe you’re perplexed since you haven’t declared a TimeSpan but have declared one? which is a TimeSpan that can’t be null. If you don’t need it to be nullable, either delete the question mark or use variable. Value.TotalHours.

Answered by Hans Olsson

Solution #3

We create two datetime objects in the example, one with the current time and the other with 75 seconds added to the current time. The method will then be called. On the second DateTime object, use Subtract(). A TimeSpan object will be returned. We can use the properties of the TimeSpan object to get the real Hours, Minutes, and Seconds once we have the TimeSpan object.

DateTime startTime = DateTime.Now;

 DateTime endTime = DateTime.Now.AddSeconds( 75 );

 TimeSpan span = endTime.Subtract ( startTime );
 Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
 Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
 Console.WriteLine( "Time Difference (hours): " + span.Hours );
 Console.WriteLine( "Time Difference (days): " + span.Days );


Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0

Answered by safi

Solution #4

Is there a good reason for you to use Nullable?

You can write variable if you want to utilise Nullable. Value.TotalHours.

Alternatively, you could simply type: (datevalue1 – datevalue2). TotalHours.

Answered by Ilya Kogan

Solution #5

Another example of subtracting two dates in C# may be found here…

if ( DateTime.Now.Subtract(Convert.ToDateTime(objDateValueFromDatabase.CreatedOn)).TotalHours > 24 ) 

Answered by Mario Levesque

Post is based on