I am retrieving two date time values from the database. Once the value is retrieved, I need the difference between the two values. For that, I create a timespan variable to store the difference of the 2 date values.
TimeSpan? variable = datevalue1 - datevalue2;
Now i need to show the difference which is stored in the Timespan variable in terms of number of hours. I referred to TimeSpan.TotalHours but couldn't apply the same for some reason. How do I do that? I am using C# on a MVC project. I simple need to show the difference value in hours?
EDIT: Since timespan was nullable, i couldn't use the total hours property. Now I can use it by doing TimeSpanVal.Value.TotalHours;
a more precise way for employee paid hours or other precision requirement::
https://dotnetfiddle.net/tVIoVJ
can also add difference between the dates if we compare two different dates
you may also want to look at
I think you're confused because you haven't declared a
TimeSpan
you've declared aTimeSpan?
which is a nullableTimeSpan
. Either remove the question mark if you don't need it to be nullable or usevariable.Value.TotalHours
.Here is another example of subtracting two dates in C# ...
In the sample, we are creating two datetime objects, one with current time and another one with 75 seconds added to the current time. Then we will call the method .Subtract() on the second DateTime object. This will return a TimeSpan object. Once we get the TimeSpan object, we can use the properties of TimeSpan to get the actual Hours, Minutes and Seconds.
Result: