How to determine the time elapsed until midnight

2

I need to determine the time until midnight.

These calculations are correct:

From 11:00 am to 12:00 pm = 01:00

From 00:00 am to 11:00 pm = 11:00

From 11:00 am to 01:00 pm = 02:00

But when the next time is calculated the result is not correct:

From 11:00 PM Until 00:00 AM = -23: 00

From 11:00 PM Until 12:00 AM = -23: 00

Here I would expect it to be = 01:00

That's what really needs to be determined, the time until midnight.

I'm doing it this way:

<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem>00:00:00 AM</asp:ListItem>
    <asp:ListItem>11:00:00 AM</asp:ListItem>
    <asp:ListItem>12:00:00 PM</asp:ListItem>
    <asp:ListItem>10:00:00 PM</asp:ListItem>
    <asp:ListItem>11:00:00 PM</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
    <asp:ListItem>00:00:00 AM</asp:ListItem>
    <asp:ListItem>11:00:00 AM</asp:ListItem>
    <asp:ListItem>12:00:00 PM</asp:ListItem>
    <asp:ListItem>01:00:00 PM</asp:ListItem>
    <asp:ListItem>12:00:00 AM</asp:ListItem>
    <asp:ListItem>11:00:00 PM</asp:ListItem>
</asp:DropDownList>

And the calculation is done as follows:

   Dim horaInicio As DateTime = DropDownList1.SelectedItem.Text
    Dim horaFin As DateTime = DropDownList2.SelectedItem.Text
    Dim diferencia As TimeSpan = horaFin.Subtract(horaInicio)
    TextBox1.Text = diferencia.ToString()
    
asked by yulfredy rodriguez 25.08.2017 в 17:17
source

2 answers

2

Good morning, The problem is that you have hours but the same day. This is how you should solve it:

Dim horaInicio As DateTime = DropDownList1.SelectedItem.Text
Dim horaFin As DateTime = DropDownList2.SelectedItem.Text

If horaFin < horaInicio Then horaFin = horaFin.AddDays(1)

Dim diferencia As TimeSpan = horaFin.Subtract(horaInicio)
TextBox1.Text = diferencia.ToString()

Greetings.

    
answered by 25.08.2017 / 17:39
source
1

When you declare a variable of type DateTime and it is initialized only with a String with the time it will be initialized with the date 01/01/0001 , which is incorrect for midnight, or in general any time it is after midnight.

For example if you want to obtain the difference of hours between 8 PM and 6 AM you would have the same problem. The algorithm you use would give you -14:00:00 when the correct would be 10:00:00

In general if the end time is less than the start time it is assumed that it is the next day so you should add one day to your horaFin

Dim horaInicio As DateTime = "08:00:00 PM"
Dim horaFin As DateTime = "06:00:00 AM"

If horaInicio > horaFin
    horaFin = horaFin.AddDays(1)
End If

Dim diferencia As TimeSpan = horaFin.Subtract(horaInicio)
TextBox1.Text = diferencia.ToString()
    
answered by 25.08.2017 в 17:44