循环总和时间跨度

时间:2019-02-20 09:59:35

标签: vb.net

我有一个计算日期TimeSpan的表格。我需要获取3个TimeSpan的总和,然后获取接下来3个等的总和。直到最后timespan

到目前为止,这是我的代码:

我能够得到TimeSpan的总和,但是仅所有总和的总和显示错误。有人可以帮我吗?

Sub HoursCalculation()
    Dim textBoxes1A() As TextBox = {TextBox1, TextBox3, TextBox5, TextBox7, TextBox9, TextBox11}
    Dim textBoxes1B() As TextBox = {TextBox2, TextBox4, TextBox6, TextBox8, TextBox10, TextBox12}
    Dim textBoxesTOT() As TextBox = {TextBox221, TextBox222, TextBox223, TextBox224, TextBox225, TextBox226, TextBox227}
    Dim total As Date
    Dim ts1 As TimeSpan
    Dim i As Integer
    Dim t As Integer

    For i = 0 To textBoxes1A.Count - 1
        If IsDate(textBoxes1A(i).Text) AndAlso IsDate(textBoxes1B(i).Text) Then
            ts1 = DateTime.Parse(textBoxes1B(i).Text).Subtract(DateTime.Parse(textBoxes1A(i).Text))
            ' Add all the differences to a total
            total = total.Add(ts1)
            textBoxesTOT(t).Text = total
        End If
    Next
End Sub

谢谢

2 个答案:

答案 0 :(得分:1)

好吧,您需要在循环的每三次运行中重置total

If i Mod 3 = 2 Then total = New TimeSpan(0) 'assuming that total is TimeSpan

该行应放在循环的末尾。

答案 1 :(得分:1)

您需要执行以下操作:

  1. 每3个添加项重置一次total的值。
  2. 每增加3次就增加t的值。
  3. (最好)而不是先使用IsDate()然后再Parse设置值,而应使用DateTime.TryParse()

您的代码应如下所示:

Sub HoursCalculation()
    Dim textBoxes1A() As TextBox = {TextBox1, TextBox3, TextBox5, TextBox7, TextBox9, TextBox11}
    Dim textBoxes1B() As TextBox = {TextBox2, TextBox4, TextBox6, TextBox8, TextBox10, TextBox12}
    Dim textBoxesTOT() As TextBox = {TextBox221, TextBox222, TextBox223, TextBox224, TextBox225,
                                     TextBox226, TextBox227}
    Dim total As TimeSpan
    Dim i, t As Integer

    For i = 0 To textBoxes1A.Count - 1
        Dim dateA, dateB As Date
        If Date.TryParse(textBoxes1A(i).Text, dateA) AndAlso Date.TryParse(textBoxes1B(i).Text, dateB) Then
            total = total.Add(dateB.Subtract(dateA))
            textBoxesTOT(t).Text = total.ToString()
            If i Mod 3 = 2 Then
                total = TimeSpan.Zero
                t += 1
            End If
        End If
    Next
End Sub

一个最终建议:尝试始终对变量和控件使用有意义的名称。避免使用TextBox1TextBox2t之类的东西(i在这里很好,尽管因为它被用作For循环的索引< / em>)。