Parker O'Connel Parker O'Connel - 1 year ago 72 Question

I am looking to determine the difference between 2 "HH:mm:ss.fff" values in VB

I am struggling to get the exact value between two cells in a datagridview. Both values are in HH:mm:ss.fff format but when i try to calc the difference i can't show the .fff in the textbox. I know that i need to format in some way but every way i try provides errors. My code is below. I do not want to show date or year in anyway and the data in the cells will always come in with HH:mm:ss.fff.

Thanks in advance. Using Visual Studio 2013

Dim value2 As DateTime = DateTime.Parse(dgvConvert(3, 1).Value)
'value is in "HH:mm:ss.fff" format i.e 08:01:05.900
Dim value1 As DateTime = DateTime.Parse(dgvConvert(3, 2).Value)
'value is in "HH:mm:ss.fff" format i.e 08:01:50.000

Dim timespan2 As DateTime = DateTime.Parse(value2)
Dim timespan1 As DateTime = DateTime.Parse(value1)

Dim duration As TimeSpan = timespan1 - timespan2

Dim duration1 As String = duration.ToString

txtResult.Text = duration1.ToString
'result is "00:00:05" but i am trying to get "00:00:05.900"
'txtResult.Text = duration(format("HH:mm:ss.fff")) does not work.

Here is the code that i use to write the CSV to the DataGridView

Private Sub btnLoadFileToConvert_Click(sender As Object, e As EventArgs) Handles btnLoadFileToConvert.Click
' MessageBox.Show("Make sure your file only contains numbers in the first coumn", "Check File")
Dim TextLine As String = ""
Dim SplitLine() As String
Dim fname As String = txtFileToConvert.Text
If System.IO.File.Exists(fname) = True Then
Dim objReader1 As New System.IO.StreamReader(fname)
Do While objReader1.Peek() <> -1
TextLine = objReader1.ReadLine()
SplitLine = Split(TextLine, ",")
MsgBox("File Does Not Exist")

End If
dgvConvert.RowCount = 6001

Answer Source

If your cells always contain a time value, you can parse them into a TimeSpan structure. Then you can subtract one from the other.

If you want to display the value showing milliseconds you can use the overload of .ToString which accepts a format (note this is slightly different to the DateTime format as some chars need to be escaped.

    'values for debug
    Dim cell2Value = "08:01:05.900" 'dgvConvert(3, 1).Value.ToString
    Dim cell1Value = "08:01:50.000" 'dgvConvert(3, 2).Value.ToString

    Dim value2 = TimeSpan.Parse(cell2Value)
    Dim value1 = TimeSpan.Parse(cell1Value)

    TextBox1.Text = (value1 - value2).ToString("hh\:mm\:ss\.fff")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download