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 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.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<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>
    <form id="form1" runat="server">
        <h2 style="color:Green">asp.net date time example: hours difference</h2>
        <br /><br />
             Text="Get Toatal Hours Difference"
More c# examples