显示剩余时间TimeSpan

时间:2013-03-18 18:16:19

标签: vb.net visual-studio datetime timer timespan

我在尝试显示操作的剩余时间时遇到问题

问题仅在于剩余的计时器,我得到负值...

这是10000毫秒(10秒)的操作示例:

enter image description here

所以无论如何,如果我从时间跨度中移除“ - ”字符,那么小时和分钟仍然会影响价值......

   Dim time_out as integer = 60000 ' 'Milisegundos

   Dim StartTime As DateTime ' Tiempo inicio
   Dim EndTime As DateTime ' Tiempo final

   Dim ElapsedTime As TimeSpan ' Tiempo transcurrido
   Dim RemainingTime As TimeSpan ' Tiempo restante


    ' Elapsed Time
#Region " Elapsed Time Function "

    Public Function Print_Elapsed_Time()
        If StartTime.ToString = "01/01/0001 0:00:00" Then
            StartTime = Now
            StartTime = StartTime.AddSeconds(-1)
        End If
        ElapsedTime = Now().Subtract(StartTime)
        Return String.Format("{0:00}:{1:00}:{2:00}", CInt(Math.Floor(ElapsedTime.TotalHours)) Mod 60, CInt(Math.Floor(ElapsedTime.TotalMinutes)) Mod 60, CInt(Math.Floor(ElapsedTime.TotalSeconds)) Mod 60)
    End Function
#End Region

#Region " Remaining Time Function "

    Public Function Print_Remaining_Time()
        If EndTime.ToString = "01/01/0001 0:00:00" Then
            EndTime = Now
            EndTime = EndTime.AddMilliseconds(Time_Out - 1000)
        End If
        RemainingTime = Now().Subtract(EndTime)
        Return String.Format("{0:00}:{1:00}:{2:00}", CInt(Math.Floor(RemainingTime.TotalHours)) Mod 60, CInt(Math.Floor(RemainingTime.TotalMinutes)) Mod 60, CInt(Math.Floor(RemainingTime.TotalSeconds)) Mod 60).Replace("-", "")
    End Function

#End Region

2 个答案:

答案 0 :(得分:2)

以下是使用计时器和两个标签

从10秒倒计时的示例
'example - countdown from 10 secs
Dim countdown As New TimeSpan(0, 0, 10)
Dim stpw As New Stopwatch

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If stpw.IsRunning Then
        stpw.Stop()
        Timer1.Stop()
    Else
        stpw.Stop()
        stpw.Reset()
        stpw.Start()
        Timer1.Interval = 100
        Timer1.Start()
    End If
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    'label1 - elapsed time
    'label2 - time remaining
    If stpw.Elapsed <= countdown Then
        Label1.Text = stpw.Elapsed.ToString
        Label2.Text = (countdown - stpw.Elapsed).ToString
    Else
        stpw.Stop()
        Label1.Text = countdown.ToString
        Label2.Text = "00:00:00"
    End If
End Sub

答案 1 :(得分:1)

我想你想要的结束时间:

RemainingTime = EndTime.Subtract(Now)

否则,我不确定你是如何初始化这些的,但我做了这个改变:

Dim StartTime As DateTime = DateTime.MinValue ' Tiempo inicio
Dim EndTime As DateTime = DateTime.MinValue ' Tiempo final

还有:

If StartTime = DateTime.MinValue Then  ' ... etc   '

但也许一面旗帜或其他东西完全是发出重置信号的更好方式。