2016-11-03 180 views
-1

遇到一個小問題 - 我有一個函數,我將DATE作爲字符串傳遞。這個日期然後作爲參數傳遞給我驗證它的存儲過程,並返回一個值(0,1),無論它是否有效。這裏是發生了什麼事情代碼明智...VB.Net驗證日期

If CheckDateSP(mskAppointment.Text) Then 
    'Great now lets use this date 
else 
    msgbox "Invalid date, re-enter please" 
End if 

它傳遞到一個函數.....

Public Function CheckDateSP(ByVal CheckThisDate As String) As Boolean 
    'Setting Connection strings and all the good stuff 
    'here's where it gives me an error 
    Dim vDate As DateTime = CheckThisDate <----HERE is the error 

End Function 

現在,這裏的有趣的部分 - 我只得到一個錯誤,如果我輸入的日期一樣...

13/13/2016

一切,如果我進入大工作完全正常TES如這些...

2017年12月12日,2014年10月10日

或者只要一個月不到13

我得到的錯誤的任何其他日期是...

從字符串'13/13/2016'轉換爲類型日期的錯誤無效。

+1

13/13 ????????? – Steve

+0

是的,我想確保這是一個有效的日期,你知道用戶如何進入上帝只知道什麼。 – BobSki

+0

'Dim vDate As DateTime = CheckThisDate'如果CheckThisDate以字符串形式傳入,則不能像這樣指定它 - convert或TryParse它(即使在Option Strict下也不會編譯) – Plutonix

回答

1

試試這個

Dim input As String = "13/13/2016" 

Dim dt As DateTime 
If DateTime.TryParseExact(input, "MM/dd/yyyy", New Globalization.CultureInfo("en-US"), Globalization.DateTimeStyles.None, dt) Then 
    MessageBox.Show(String.Format("The string '{0}' parsed to '{1:yyyy-MM-dd hh:mm:ss}'", input, dt)) 
Else 
    MessageBox.Show(String.Format("Couldn't parse '{0}'", input)) 
End If 

的調用TryParseExact返回true,當它在正確的格式,並假時,它不是。請注意,提供給TryParseExact的格式爲月/日/年,我使用Globalization.CultureInfo("en-US"),因爲我在美國。

+1

非常感謝。 – BobSki

+1

這太糟糕了,你不能使用DateTimePicker而不是MaskedTextBox。它返回一個DateTime,所以你不需要爲此煩惱。 – djv