1

在 VB.net 中,我一直在学习 Murach 的 Visual Basic 2010。在学习如何处理时间和字符串时,我遇到了时间跨度的问题。

我需要两个日期并找出它们之间的天数。

所以我声明了我的变量。

Dim currentDay As Date
Dim futureDate As Date
Dim timespan As TimeSpan = currentDay.Subtract(futureDate)
Dim strMsgText As String
Dim daysUntilDue = timespan.Days

然后我为 currentDay 和 futureDate 设置格式

currentDay = Convert.ToDateTime(Now)
futureDate = Convert.ToDateTime(txtFutureDate.Text) 'input from user

然后我设置我需要显示的数据

 strMsgText = "Current Date: " & currentDay.ToShortDateString() _
            & "Future Date: " & futureDate.ToShortDateString() _
            & "Days Util Due " & daysUntilDue

接下来我提供了数据验证

If IsDate(txtFutureDate.Text) Then
   futureDate = CDate(txtFutureDate.Text)
End If

最后我显示数据

MessageBox.Show(strMsgText)

我没有收到来自 vb ide 的语法错误或错误,但是,当它计算日期时,它在消息框中给了我这个

前任。

Current Date: 3/30/2013

Future Date: 12/26/2013

 Days Until Due: 0

我试图翻转计算中的日期

前任。而不是currentDay.Subtract(futureDate)我设置它futureDate.Subtract(currentDay)只是为了看看它是否会给我一个不同的结果。但是,唉,它仍然是 0。

我知道我做错了什么,但我无法找出IDE /编译器没有给我任何错误,这本书没有给我任何建议或知道如何让它正常工作.

4

2 回答 2

2

问题在于,当时您正在设置时间跨度值currentDay并且futureDate尚未初始化并且具有 a 的默认值DateTime。这些的减法将始终为 0 TimeSpan

在设置这两个日期timespan 后设置。

Dim currentDay As Date
Dim futureDate As Date
Dim strMsgText As String

currentDay = Convert.ToDateTime(Now)
futureDate = Convert.ToDateTime(txtFutureDate.Text) 'input from user

Dim timespan As TimeSpan = currentDay.Subtract(futureDate)
Dim daysUntilDue = timespan.Days
于 2013-03-30T19:41:54.033 回答
0

由于您需要检查用户是否输入了有效日期,您可以使用 DateTime.TryParse 来确定:

Dim currentDay As Date = DateTime.Now
Dim futureDate As Date
Dim strMsgText As String
Dim daysUntilDue As Integer

currentDay = DateTime.Now

Dim ci As New Globalization.CultureInfo("en-US")

' check if a parseable date has been entered before doing the calculation
If DateTime.TryParse(txtFutureDate.Text, ci, Globalization.DateTimeStyles.AllowWhiteSpaces, futureDate) Then
    daysUntilDue = (futureDate - currentDay).Days
    strMsgText = "Current Date: " & currentDay.ToShortDateString() & " Future Date: " & futureDate.ToShortDateString() & " Days Until Due " & daysUntilDue.ToString
Else
    strMsgText = "I could not understand the future date as entered."
End If

MessageBox.Show(strMsgText)
于 2013-03-30T19:53:34.550 回答