在Visual Basic中遇到TimeSpan问题

时间:2013-03-30 19:35:41

标签: .net vb.net timespan

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

我需要花2个日期并找到它们之间的天数。

所以我宣布了我的变量。

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 /编译器没有给我任何错误,书没有给我任何建议或知道如何得到这个工作正常。

2 个答案:

答案 0 :(得分:2)

问题是,当您设置时间跨度值currentDayfutureDate尚未初始化且具有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

答案 1 :(得分: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)