vb.net 验证日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15453056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validate the date format
提问by user1795999
I have a textboxin my form in vb 2010 which should accept only dates and only in the format of "yyyy/mm/dd"
我textbox在 vb 2010 中有一个表单,它应该只接受日期并且只接受格式为"yyyy/mm/dd"
How to achieve this? Please help
如何实现这一目标?请帮忙
回答by spajce
Private Sub TextBox2_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox2.Validating
Dim test As Date
If Date.TryParseExact(TextBox2.Text.ToString(), "yyyy/mm/dd", _
System.Globalization.CultureInfo.CurrentCulture, _
Globalization.DateTimeStyles.None, test) Then
MessageBox.Show("Ok")
'TODO: ok
Else
e.Cancel = True
'TODO: not ok
End If
End Sub
回答by Pierre-Olivier Pignon
You can try this:
你可以试试这个:
DateTime.TryParseExact(dateToTest, "yyyy/MM/dd", New CultureInfo("us-US"), DateTimeStyles.None, result)
回答by DevelopmentIsMyPassion
If you use datepicker control then you can set to custom format as you like. In the form load event use below
如果您使用 datepicker 控件,那么您可以根据需要设置为自定义格式。在下面的表单加载事件中使用
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "yyyy/mm/dd"
Let me know if it helps.
如果有帮助,请告诉我。

