ASP.NET C#

How to get hours between two DateTimes in C#2 min read

The following asp.net c# example code demonstrate us how can we get number of hours between two DateTime objects programmatically at run time in an asp.net application.

.Net framework’s DateTime Class DateTime.Subtract(DateTime) overloaded method allow us to subtract a specified date and time from this instance. DateTime.Subtract() method need to pass a DateTime object to subtract from specified DateTime object.




This method return a System.TimeSpan value. This TimeSpan represent a time interval that is equal to the date and time represented by this instance minus the date and time passed by parameter.

TimeSpan.TotalHours property allow us to get the value of the current TimeSpan structure expressed in whole and fractional hours.

TimeSpan.Hours property allow us to get the hours component of the time interval represented by the current TimeSpan structure. This property return value type is System.Int32.

So, we can get total hours difference between two DateTime objects by this way. First, we subtarct two DateTime objects using DateTime.Subtract(DateTime) method. Next, we get the total hours and fraction of hours from the returned TimeSpan object using TimeSpan.TotalHours property. We also can get the total hours difference without fraction of hours by using TimeSpan.Hours property.

Example Output:

c# - How to get hours between two DateTimes

c# – How to get hours between two DateTimes

ASP.NET Code:

 

 

Leave a Comment