java404
java404

Reputation: 171

Get the Number of Hours Between Two Times In Asp.net

I have a 3 textbox in .aspx.
1. txtStartTime
2. txtEndTime
3. txtNumberOfHours

I want to auto calculate number of hours in txtNumberOfHours

Here is my Code :

TestNumOfHour.aspx

<asp:TextBox ID="txtStartTime" runat="server" ontextchanged="txtStartTime_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:TextBox ID="txtEndTime" runat="server" ontextchanged="txtEndTime_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:TextBox ID="txtNumberOfHours" runat="server"></asp:TextBox>

NumOfHour.aspx.cs

  protected void txtEndTime_TextChanged(object sender, EventArgs e)
    {
        txtNumberOfHours.Text = calculateTimeDiff(txtStartTime.Text, txtEndTime.Text).ToString();
    }
    protected void txtStartTime_TextChanged(object sender, EventArgs e)
    {
        txtNumberOfHours.Text = calculateTimeDiff(txtStartTime.Text, txtEndTime.Text).ToString();
    }

    private TimeSpan calculateTimeDiff(string t1, string t2)
    {
        TimeSpan ts = TimeSpan.Zero; 
        DateTime tt1, tt2;
        if (DateTime.TryParse(t1, out tt1) && DateTime.TryParse(t2, out tt2))
        {
            ts = tt2.Subtract(tt1);
        }
        return ts;
    }

I only want Hours exclude Minutes and seconds but somehow I getting this result.

The Result in txtNumberOfHours : hr:mins:seconds

Upvotes: 3

Views: 681

Answers (2)

Anagha
Anagha

Reputation: 136

txtNumberOfHours.Text = (t2 - t1).TotalHours.ToString();

This statement is returning the number of hours.

Upvotes: 1

gidanmx2
gidanmx2

Reputation: 469

Try this:

(DateTime.Parse(t2) - DateTime.Parse(t1)).TotalHours

Upvotes: 0

Related Questions