开始时间为11:30:25PM
,结束时间为11:45:25AM
现在我想要得到结束时间和开始时间之间的差值
这是我使用的下面的代码,工作得很好:
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = Now.ToString("h:mm:ss tt")
Dim sDateTo As String = txtlogout1.Text
If DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Timer1.Start()
Dim TS As TimeSpan = dTo - dFrom
Dim hour As Integer = TS.Hours
Dim mins As Integer = TS.Minutes
Dim secs As Integer = TS.Seconds
Dim timeDiff As String = ((hour.ToString("00") & ":") + mins.ToString("00") & ":") + secs.ToString("00")
txtremaining1.Text = timeDiff
End If
现在的问题是,如果开始时间是11:30:25PM
,结束时间是12:00:25AM
,那么剩余的时间显示为-23:30:00
那么正确的处理方法是什么呢?
你只关心跨越一天吗?你能不能检查一下你的Timespan
变量是否为负,如果是加一天?
If TS.TotalMilliseconds < 0 Then TS = TS.Add(TimeSpan.FromDays(1))
If DateTime.TryParse(txtlogout1.text, dTo) Then
Dim ts as Timespan = dTo.Subtract(DateTime.now)
If ts.TotalMilliseconds < 0 Then ts = ts.Add(TimeSpan.FromDays(1))
txtremaining1.Text = ts.ToString()
End If