Question

In my project I created a label to show a start time and two buttons to adjust it, one is add 15min for each click, the other is subtract 15min. The code is as follows

Label1.text = "04:30 AM"
Private Sub Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Add.Click, Btn_Sub.Click
Dim btn_clicked As Button = Ctype(sender, Button)
If btn_clicked.Name = "Btn_Add" Then
    Label1.text = Ctype(Label.text, DateTime).AddMinutes(15).ToString("hh:mm tt")
ElseIf btn_clicked.Name = "Btn_Sub" Then
    Label1.text = Ctype(Label.text, DateTime).AddMinutes(-15).ToString("hh:mm tt")
End If
End Sub

The buttons are work fine at first, but if I keep clicking subtract button, I hope the time will change as a cycle, for example, 4:30 AM -> 4:15 AM ->... ->12:15 AM -> 12:00 AM -> 11:45 PM -> 11:30 PM

But once the jump mid-night event happens the exception throw out,

System.ArgumentOutOfRangeException was unhandled Message="Specified argument was out of the range of valid values."

How would that happen? The min value for datetime is 00:00:00.0000000, January 1, 0001 base on MSDN. Do I need to assign a year date as initial value?

Thanks!

Was it helpful?

Solution

Try it like this

Private Sub Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Add.Click, Btn_Sub.Click
    Dim btn_clicked As Button = CType(sender, Button)
    Static startTime As DateTime = #12/30/5000 4:30:00 AM#
    If btn_clicked.Name = "Btn_Add" Then
        startTime = startTime.AddMinutes(15)
        Label1.text = startTime.ToString("hh:mm tt")
    ElseIf btn_clicked.Name = "Btn_Sub" Then 'in the OP this said Btn_Add also
        startTime = startTime.AddMinutes(-15)
        Label1.text = startTime.ToString("hh:mm tt")
    End If
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top