VB.NET中如何提取生产单元首尾时间戳计算耗时?
Great question! Instead of trying to extract timestamps from the ListBox items later (which would require re-parsing strings unnecessarily), the most efficient approach is to track the first and last timestamps as you read the file. Here's how to implement this in your existing code:
Step 1: Add Variables to Track Timestamps
First, declare nullable DateTime variables at the class level to hold the first and last times for each production cell. Nullable types let us check if we've received any records yet:
Private firstTimeCell1 As DateTime? Private lastTimeCell1 As DateTime? Private firstTimeCell2 As DateTime? Private lastTimeCell2 As DateTime?
Step 2: Modify File Reading Logic to Parse Timestamps
Instead of relying on String.Contains to check for cell names and colors, split each line into its components using the comma separator. This makes parsing the timestamp and color number much more reliable:
In your btnBrowse_Click method, replace the inner loop with this code:
While Not srFile.EndOfStream strLine = srFile.ReadLine ' Split the line into parts (cell name, timestamp, color number) Dim parts() As String = strLine.Split({", "}, StringSplitOptions.None) If parts.Length = 3 Then Dim cellName As String = parts(0) Dim timestampStr As String = parts(1) Dim colorNum As String = parts(2) ' Parse the timestamp (handle invalid dates gracefully) Dim timestamp As DateTime If DateTime.TryParse(timestampStr, timestamp) Then ' Process Production Cell 1 If cellName = "Production Cell 1" Then lstProductionCell1.Items.Add(strLine) ' Update first and last timestamps If firstTimeCell1 Is Nothing Then firstTimeCell1 = timestamp End If lastTimeCell1 = timestamp ' Always update to the latest record ' Count colors using the parsed color number Select Case colorNum Case "1" white1 += 1 lblWhiteCell1.Text = white1.ToString() Case "2" black1 += 1 lblBlackCell1.Text = black1.ToString() Case "3" red1 += 1 lblRedCell1.Text = red1.ToString() Case "4" yellow1 += 1 lblYellowCell1.Text = yellow1.ToString() Case "5" green1 += 1 lblGreenCell1.Text = green1.ToString() Case "6" blue1 += 1 lblBlueCell1.Text = blue1.ToString() Case "7" brown1 += 1 lblBrownCell1.Text = brown1.ToString() Case "8" grey1 += 1 lblGreyCell1.Text = grey1.ToString() End Select ' Process Production Cell 2 ElseIf cellName = "Production Cell 2" Then lstProductionCell2.Items.Add(strLine) ' Update first and last timestamps If firstTimeCell2 Is Nothing Then firstTimeCell2 = timestamp End If lastTimeCell2 = timestamp ' Always update to the latest record ' Count colors using the parsed color number Select Case colorNum Case "1" white2 += 1 lblWhiteCell2.Text = white2.ToString() Case "2" black2 += 1 lblBlackCell2.Text = black2.ToString() Case "3" red2 += 1 lblRedCell2.Text = red2.ToString() Case "4" yellow2 += 1 lblYellowCell2.Text = yellow2.ToString() Case "5" green2 += 1 lblGreenCell2.Text = green2.ToString() Case "6" blue2 += 1 lblBlueCell2.Text = blue2.ToString() Case "7" brown2 += 1 lblBrownCell2.Text = brown2.ToString() Case "8" grey2 += 1 lblGreyCell2.Text = grey2.ToString() End Select End If End If End If End While
Step 3: Calculate and Display Duration
After closing the file, compute the time difference between the first and last timestamps for each cell and display it (add labels like lblDurationCell1 and lblDurationCell2 to your form first):
srFile.Close() ' Be sure to close the file ' Calculate duration for Production Cell 1 If firstTimeCell1 IsNot Nothing AndAlso lastTimeCell1 IsNot Nothing Then Dim duration As TimeSpan = lastTimeCell1.Value - firstTimeCell1.Value lblDurationCell1.Text = $"Cell 1 Total Duration: {duration.Hours}h {duration.Minutes}m {duration.Seconds}s" Else lblDurationCell1.Text = "No data for Production Cell 1" End If ' Calculate duration for Production Cell 2 If firstTimeCell2 IsNot Nothing AndAlso lastTimeCell2 IsNot Nothing Then Dim duration As TimeSpan = lastTimeCell2.Value - firstTimeCell2.Value lblDurationCell2.Text = $"Cell 2 Total Duration: {duration.Hours}h {duration.Minutes}m {duration.Seconds}s" Else lblDurationCell2.Text = "No data for Production Cell 2" End If
Key Improvements:
- Efficient Timestamp Tracking: We capture timestamps as we read the file, avoiding re-parsing strings from ListBox items later.
- Reliable Parsing: Using
Splitinstead ofContainsmakes the code less error-prone (e.g., no false matches if a timestamp accidentally contains "1"). - Error Handling:
DateTime.TryParseensures invalid timestamps don't crash your app. - Cleaner Color Counting: The
Select Casestatement replaces the long chain ofIf/ElseIfchecks for colors.
内容的提问来源于stack exchange,提问作者AaronM

