2016-11-03 182 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