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.
1 2 3 |
TimeSpan difference = myDate2.Subtract(myDate1); |
Example Output:
ASP.NET Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<%@ 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>code4example.com</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <br /> <form id="form1" runat="server"> <div class="container"> <div class="alert alert-primary" role="alert"> <h2> asp.net date time example:<strong> hours difference </strong> </h2> </div> <asp:Label ID="Label1" runat="server" CssClass="alert alert-success d-block" > </asp:Label> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" CssClass="btn btn-danger btn-lg" Text="Get Toatal Hours Difference" /> </div> </form> </body> </html> |