vb.net 以分钟为单位的日期和时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17765319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date and Time Difference in Minutes
提问by user2602702
Is there any way to Display the difference between 2 different times. I currently have 2 buttons.
有什么方法可以显示2个不同时间之间的差异。我目前有 2 个按钮。
Sub AddButtonClick(sender As Object, e As EventArgs)
StartTime.Text = DateTime.Now.ToString()
End Sub
This generates the first timestamp
这将生成第一个时间戳
Sub EndBreakClick(sender As Object, e As EventArgs)
EndTime.Text = DateTime.Now.ToString()
DateDiff(DateInterval.Minute, Endtime, StartTime)
End Sub
This generates the second timestamp but the datediff line causes the app to crash as soon as I press the button.
这会生成第二个时间戳,但 datediff 行会导致应用程序在我按下按钮后立即崩溃。
回答by varocarbas
You can rely on TimeSpan
:
您可以依赖TimeSpan
:
Dim elapsedTime As TimeSpan = DateTime.Parse(EndTime.Text).Subtract(DateTime.Parse(StartTime.Text))
It behaves as a normal time variable from which you can extract all the information you want. Example:
它表现为一个正常的时间变量,您可以从中提取所需的所有信息。例子:
Dim elapsedMinutesText As String = elapsedTime.Minutes.ToString()
Bear in mind that the code above takes string variables as inputs (the text from your textboxes) because it performs the corresponding conversion: Convert.ToDateTime
.
请记住,上面的代码需要字符串变量作为输入(从你的文本框文本),因为它执行相应的转换:Convert.ToDateTime
。
Regarding your code, it refers to EndTime
and StartTime
and these are not DateTime
variables, but TextBoxes
. You have to convert them (their text) into DateTime
as I am doing above, that is:
关于您的代码,它指的是EndTime
和StartTime
,这些不是DateTime
变量,而是TextBoxes
. 您必须DateTime
像我上面所做的那样将它们(它们的文本)转换为:
DateDiff(DateInterval.Minute, DateTime.Parse(EndTime.Text), DateTime.Parse(StartTime.Text))
回答by OneFineDay
The DateDifffunction will do it.
该则DateDiff函数将做到这一点。
label1.text = DateDiff("n", DateTime.Parse(EndTime.Text), DateTime.Parse(StartTime.Text)).ToString
If your app is crashing, did you check the variable you tried to pass to it? It looks like your trying to pass the textbox
to it and not the textbox.text
.
如果您的应用程序崩溃,您是否检查了尝试传递给它的变量?看起来您试图将 传递textbox
给它而不是textbox.text
.
回答by Douglas Barbin
Sub EndBreakClick(sender As Object, e As EventArgs)
EndTime.Text = DateTime.Now.ToString()
Dim myStartTime As DateTime? = If(DateTime.TryParse(StartTime.Text, myStartTime), myStartTime, Nothing)
Dim myEndTime As DateTime? = If(DateTime.TryParse(EndTime.Text, myEndTime), myEndTime, Nothing)
If myStartTime.HasValue AndAlso myEndTime.HasValue Then
Dim someVariable As Long = DateDiff(DateInterval.Minute, myStartTime.Value, myEndTime.Value)
' DO SOMETHING WITH THAT VARIABLE HERE
Else
' One or both of the textbox values wasn't a valid DateTime. Display an error message or something
End If
End Sub