[c#] Showing Difference between two datetime values in hours

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;

This question is related to c# asp.net-mvc-2 datetime timespan

The answer is


Is there a reason you're using Nullable?

If you want to use Nullable then you can write variable.Value.TotalHours.

Or you can just write: (datevalue1 - datevalue2).TotalHours.


Here is another example of subtracting two dates in C# ...

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

a more precise way for employee paid hours or other precision requirement::

decimal DeterminePreciseHours(DateTime startTimestamp, DateTime stopTimestamp)
{
    var span = (stopTimestamp - startTimestamp).Value;
    decimal total = (decimal)span.TotalMilliseconds / 60 / 60 / 1000;
    return Math.Round(total, PRECISION_CONSTANT);
}

https://dotnetfiddle.net/tVIoVJ


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.

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

Result:

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

WOW, I gotta say: keep it simple:

MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));

Result: True

and:

MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));

Result: 10.00:00:00

The DateTime object has all the builtin logic to handle the Boolean result.


you may also want to look at

var hours = (datevalue1 - datevalue2).TotalHours;

var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM 
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)

can also add difference between the dates if we compare two different dates

new TimeSpan(24 * days, 0, 0)

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc-2

Better solution without exluding fields from Binding How to set the value of a hidden field from a controller in mvc Making a Simple Ajax call to controller in asp.net mvc ASP.Net MVC - Read File from HttpPostedFileBase without save Session state can only be used when enableSessionState is set to true either in a configuration Using Tempdata in ASP.NET MVC - Best practice Getting index value on razor foreach Current date and time - Default in MVC razor Url.Action parameters? How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to timespan

How to Convert string "07:35" (HH:MM) to TimeSpan Check if a given time lies between two times regardless of date Measuring code execution time Work with a time span in Javascript Getting time span between two times in C#? TimeSpan to DateTime conversion What is the correct SQL type to store a .Net Timespan with values > 24:00:00? Check if datetime instance falls in between other two datetime objects Showing Difference between two datetime values in hours C#: what is the easiest way to subtract time?