Need to find the TimeSpan between two DateTime objects

133 Views Asked by At

I have a text file that contains the following: Process started 2023/03/04 22:17:53 ... Process completed 2023/03/04 22:18:40

I use Visual Studio 2022 and .NET 6

I want to be able to read these fields in, calculate a time difference, then take the time difference and convert it into a string to be able to show in MessageBox() later on.

Public Shared Function CalcTime(Index As Byte) As TimeSpan
    Dim duration As New TimeSpan
    Dim startTime As New DateTime(22, 17, 53)
    Dim endTime As New DateTime(22,18,40)
    duration = endTime - startTime

    Return duration
End Function

I get Error BC30311 Value of type 'TimeSpan' cannot be converted to 'TimeSpan'

If I change the last line to:

duration = endTime.Subtract(startTime)

Results in same message

Test()
Dim duration As TimeSpan
Dim durStr As String
duration = CalcTime(0)
durStr = String.Format("{0:hh\\:mm\\:ss}", duration)
                    Try
                        durStr = String.Format("{0:hh\\:mm\\:ss}", duration)
                    Catch e As FormatException
                        durStr = "Invalid Format"
                    End Try

The string formatted time difference goes into this string:

Dim TimeDiff1Str As String = "Time diff " & durStr & " for " & vbCrLf

Does anyone have a clear and concise method to do what I am attempting to do? Thank you.

Based on searches on the Internet, I expected at least some of the snippets to work. I did notice that there is not always clear vb.net code, as TimeSpan objects occur in other languages as well.

1

There are 1 best solutions below

0
Niya On

Try this:-

    Public Function GetTimeDiff(ByVal earlyDate As DateTime, ByVal lateDate As DateTime) As String

        Dim diff = lateDate.Subtract(earlyDate)

        Dim timeParts = {If(diff.Days <> 0, $"{diff.Days} days", Nothing),
                         If(diff.Hours <> 0, $"{diff.Hours} hours", Nothing),
                         If(diff.Minutes <> 0, $"{diff.Minutes} minutes", Nothing),
                         If(diff.Seconds <> 0, $"{diff.Seconds} seconds", Nothing)}


        Return String.Join(", ", From s In timeParts Where s IsNot Nothing)

    End Function

The above function takes two dates and calculates the difference and returns a String describing the difference in time in a human readable way. You can test it with this:-

        Dim late As DateTime = Date.Now

        Dim earlyDates = {late.Subtract(TimeSpan.FromMinutes(20)),
                          late.Subtract(TimeSpan.FromHours(16.4)),
                          late.Subtract(TimeSpan.FromDays(70.934)),
                          late.Subtract(TimeSpan.FromDays(120.5))}


        For Each ed In earlyDates
            Debug.WriteLine(GetTimeDiff(ed, late))
        Next

Which would give an output like this:-

20 minutes
16 hours, 24 minutes
70 days, 22 hours, 24 minutes, 57 seconds
120 days, 12 hours