c# - How to get hours between two DateTimes

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

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

This method return a System.TimeSpan value. This TimeSpan represent a time interval that is equalto 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 wholeand fractional hours.

TimeSpan.Hours property allow us to get the hours component of the time interval represented by the currentTimeSpan 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 usingDateTime.Subtract(DateTime) method. Next, we get the total hours and fraction of hours from the returned TimeSpan objectusing TimeSpan.TotalHours property. We also can get the total hours difference without fraction of hours by using TimeSpan.Hoursproperty.
TotalHours.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime myDate1 = DateTime.Now;
        DateTime myDate2 = DateTime.Now.AddDays(8);
        TimeSpan difference = myDate2.Subtract(myDate1);

        double totalHours = difference.TotalHours;

        Label1.Text = "MyDate1: " + myDate1.ToString();
        Label1.Text += "<br />MyDate2: " + myDate2.ToString();
        Label1.Text += "<br /><br />Total Hours Difference: " + totalHours;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to get total hours difference between two date time object</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net date time example: hours difference</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             Font-Italic="true"
             Font-Bold="true"
             ForeColor="Navy"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="Navy" 
             OnClick="Button1_Click"
             Text="Get Toatal Hours Difference"
             />   
    </div>
    </form>
</body>
</html>