3

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

java404
  • 171
  • 1
  • 11
  • Are the inputs "abstract times of day" or (date)times on *particular* days? If the latter, do you need to take DST into account? – Damien_The_Unbeliever Apr 02 '19 at 09:10
  • 1
    Look into `TimeSpan.Hours` and into `TimeSpan.ToString(string)` – Zohar Peled Apr 02 '19 at 09:12
  • 2
    Possible duplicate of [Days, hours, minutes, seconds between two dates](https://stackoverflow.com/questions/10538507/days-hours-minutes-seconds-between-two-dates) – Mihir Apr 02 '19 at 09:12
  • 1
    You might also want to consider making this all less "stringly-typed". There's no reason why the `calculateTimeDiff` method should be parsing strings. It's inputs should be `DateTime`s already. – Damien_The_Unbeliever Apr 02 '19 at 09:13
  • What is the expected result if startTime is `00:00:00` and so is endTime? What if startTime is `00:00:00` and endTime is `23:59:59`? What if startTime is `23:00:00` and `endTime` is `01:00:00`? – mjwills Apr 02 '19 at 09:36
  • Possible duplicate of [Calculate difference between two dates (number of days)?](https://stackoverflow.com/questions/1607336/calculate-difference-between-two-dates-number-of-days) – Kami Apr 02 '19 at 10:46

2 Answers2

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

This statement is returning the number of hours.

Torbjörn Hansson
  • 18,354
  • 5
  • 33
  • 42
Anagha
  • 136
  • 3
0

Try this:

(DateTime.Parse(t2) - DateTime.Parse(t1)).TotalHours
gidanmx2
  • 469
  • 1
  • 9
  • 24