VB.NET确定两个日期和时间之间的时差

时间:2014-10-01 13:41:41

标签: vb.net

我几天来一直在寻找这个答案,找不到简单的解决方案。我有一个简单的表格,有两个按钮" JOB START" &安培; "工作完成"。按钮文本等于日期/时间"现在"一旦被迫我想做的就是有一个标签显示一次完成的时间" JOB FINISHED"以hh:mm:ss

的格式按下
Me.btnStart.Text = 10/1/2014 05:30:00
Me.btnStop.Text = 10/1/2014 06:45:00

' Result should read:
Me.Label1.Text = 01:15:00

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

目前尚不清楚您是Dates还是仅Strings。如果是后者,您首先必须使用Date.Parse(btnStart.Text)Date.TryParse(btnStart.Text, dateVariable)来解析字符串。

但是,如果您有两个日期,则可以从dt1 - dt2计算返回TimeSpan对象的持续时间,TimeSpan.ToString返回所需的字符串:

Dim stopDate As Date
Dim stopIsDate As Boolean = Date.TryParse(btnStop.Text, stopDate)
Dim startDate As Date
Dim startIsDate As Boolean = Date.TryParse(btnStart.Text, startDate)
If stopIsDate AndAlso startIsDate Then
    Dim diff As TimeSpan = stopDate - startDate
    Me.Label1.Text = diff.ToString("hh\:mm\:ss")
End If

另一种方法是创建一个忽略日期的DateTime,然后您可以使用ToLongTimeString之类的所有Date方法。提供正确的格式也更​​容易:

Dim time As Date = Date.Today.Add(diff) ' Add takes a TimeSpan
Me.Label1.Text = time.ToLongTimeString() 
' or '
Me.Label1.Text = time.ToString("T")
' or '
Me.Label1.Text = time.ToString("HH:mm:ss") ' upper-case HH is 24h clock '

Standard Date and Time Format Strings

答案 1 :(得分:1)

公共类FMain

Dim startTime As DateTime
Dim endTime As DateTime
Dim duration As TimeSpan

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      startTime = DateTime.Now
    A1.Text = startTime.ToString("hh\:mm\:ss") ' A1 is a text box
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    endTime = DateTime.Now
    A2.Text = endTime.ToString("hh\:mm\:ss")
    duration = endTime - startTime
    A3.Text = duration.ToString("hh\:mm\:ss")
End Sub

结束班级