Search code examples
vb.netdatetimedateparser

Having trouble with DateParse and 24hr clock when comparing 2 times


I have a solution where files with differing filenames need to be matched into pairs before processing. Although the files have differing names, as part of the name they both contain a timestamp as part of the filename. Before matching, I need to ensure that the 2nd part of the pair is within 90minutes of the first based on this timestamp. The client process creates 3 pairs a day so I need to ensure I match first run with first run and second run with second and so on.

The code is working fine except for where the second run is after midday and although the timestamp is in HHmm, the value returned from DateParse will not be.

 Dim datIDTIme = Date.ParseExact(datID, "HHmm", Globalization.DateTimeFormatInfo.InvariantInfo)
 Dim runIDTIme = Date.ParseExact(strRunID, "HHmm", Globalization.DateTimeFormatInfo.InvariantInfo)
 If DateDiff(DateInterval.Minute, datIDTIme, runIDTIme) < 90 Then ...

So for a file that had 1446 in the filename: I get back this as value #10/26/2023 02:46:00 PM# and the DateDiff would return -361 like it has counted back to 2am. How do I force it to return the time as 24hr?

datID is 1446 (PAG129D-PRFREST~PPCB02~CBF001D~T~PAG129D-1446_231024_1050795000.DAT) strRunID is 0845 (T.PR.IPW.PSL1311.11082023.0845.PERS.0.1042083000.STEP3.162.194.AFP)


Solution

  • If you write

    Dim delta = (runIDTIme - datIDTIme).Duration
    

    then delta will be a TimeSpan with the absolute value of the difference. You can use things like delta.TotalMinutes to get the value of the timespan in minutes, or (as pointed out by user jmcilhinney in a comment) for the example in the question you might use something like:

    If delta <= TimeSpan.FromMinutes(90) Then
    

    which makes it easy to see that you mean 90 minutes.