Search code examples
vb.nettimetextboxformatnumericupdown

Converting String And Time Formats


I have a simple textbox and a a numericupdown. I need to convert the result in the textbox to a 0:00:00 time format. So if the numericupdown says "2", the textbox says "1:58:00". This is for a timer I am working on, and I just keep bumping my head on this one. If any one can help this simple coders block, I'd be much very thankful!

Public Class Form1

Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged
    TextBox1.Text = 120 - NumericUpDown1.Value
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    TextBox1.Text = 120 - NumericUpDown1.Value
End Sub
End Class

Solution

  • There are basically two (good) ways of doing this.

    1. Create a date and add/subtract minutes as desired and then turn that into a string.
    2. Create a TimeSpan and add/subtract the difference.

    Here's an example of (2)

        dim baseTm as TimeSpan = New TimeSpan(2, 0,0)
        Dim offset as TimeSpan = New TimeSpan(0,NumericUpDown1.Value, 0)
    
        Console.WriteLine(baseTm.Subtract(offset).ToString("HH\:mm\:ss", New CultureInfo("en-US" )))
    

    An example of (1) would be something like:

        Dim baseDt as DateTime =#2:00#
        Console.WriteLine(baseDt.AddMinutes(-NumericUpDown1.Value).ToString("HH:mm:ss"))
    

    You can also just do the math yourself, but despite it being easy, using dates is clearer, anyway for the sake of covering all the bases...

        num = 120 - NumericUpDown1.Value
        Dim hr as Integer = num \ 60
        Dim mn As Integer = num - (hr*60)
        Dim str As String = hr.ToString()
        Dim str1 As String =  mn.ToString("00")
        TextBox1.Text = str1 & ":" & str2 & ":00"