2014-02-27 96 views
0

我正在嘗試減去兩次。減去VB.net中的時間

Sub notifier(checkouttime As Label) 
     Dim checktime As New DateTime(checkouttime.Tag) 
     Dim currenttime As New DateTime(DateAndTime.TimeOfDay.ToString("hh:mm:ss")) 

     Dim balance As TimeSpan = checktime - currenttime 
    End Sub 

我checkouttime.tag下具有這種格式的時間值「HH:MM:SS」

,我必須得到當前時間與今天相同的格式,我實現它,但當我需要扣除他們時,我收到一個錯誤。

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll 

Additional information: Conversion from string "08:00:58" to type 'Long' is not valid. 

在此先感謝

+0

它有助於編譯選項嚴格上的代碼了一段時間,以避免陷阱這樣。你需要'Dim checktime As New DateTime(CStr(checkouttime.Tag))' –

回答

0

這將嘗試解析您的DateTime字符串。您可能需要保存日期並保存到您的Tag屬性。

Private Function Notifier(checkouttime As Label) As String 
    Dim checktime As DateTime 
    If DateTime.TryParse(checkouttime.Tag.ToString, checktime) Then 
    Dim currenttime As Date = Date.Now 
    Return (currenttime - checktime).ToString() 
    End If 
    Return "Bad Time String" 
End Sub 
+0

實際上它們都有一個值。我把它放在消息框中,我已經看到它們是檢查時間和當前時間的價值。 另外,我想知道這兩次之間的平衡,所以我可以創建一個if else語句。 –

0

嘗試這種格式...

Dim date1 As Date = #2/14/2014 9:35:04 AM# 
Dim date2 As Date = #2/28/2014 12:30:54 PM# 
Dim duration As TimeSpan = date1 - date2 

MsgBox(duration.ToString) 
0

沒關係,我已經找到了我的問題,另一個類似的解決方案,這裏是我如何解決這個問題。

Sub notifier(checkouttime As Label) 
     Dim checktime As String = checkouttime.Tag 
     Dim splitcheck = Split(checktime, ":") 
     Dim currenttime As String = CStr(DateAndTime.TimeOfDay.ToString("hh:mm:ss")) 
     Dim splitcurrent = Split(currenttime, ":") 

     Dim checkMinutes, currentMinutes As Integer 

     checkMinutes = CDbl(splitcheck(0)) * 60 + CDbl(splitcheck(1)) + CDbl(splitcheck(2))/60 
     currentMinutes = CDbl(splitcurrent(0)) * 60 + CDbl(splitcurrent(1)) + CDbl(splitcurrent(2))/60 

     'Dim balance As String = checkkresult - currentresult 

     MsgBox(checkMinutes & " " & currentMinutes & ". While current time is: " & currenttime) 
    End Sub 

我將時間轉換爲分鐘以實現我的目標。

謝謝您的回答傢伙。