check & convert from a string to date vb.net

白昼怎懂夜的黑 提交于 2019-12-01 21:59:11

问题


I am a beginner in VB.NET & I am stuck at a very simple thing, Date formats.

I am working on an application which uploads data from excel sheets into sql server database. The application will accept dates only if they are in mm/dd/yyyy format. It should reject all dates otherwise.

Now i am struggling to check its format. Here is my code.

Dim ROHSDate As String
ROHSDate = Trim(filterString(holdingTank))
... 
here i need to check if it is in mm/dd/yyyy format

Please help.


回答1:


Use DateTime.TryParseExact, which allows you to specify the format - it will attempt to parse it, putting the parsed value into an output parameter on success, and return success/failure:

Dim dt As DateTime
If (DateTime.TryParseExact(ROHSDate, "mm/dd/yyyy", \
                           CultureInfo.InvariantCulture, \
                           DateTimeStyles.None, \
                           Out dt))
    UseDateTime(dt)
End If

Obviously, add Else clauses etc if you need them.

(I believe in modern VB the line continuations may be unnecessary, but hey... hopefully you get the point.)

Note that I've explicitly used CultureInfo.InvariantCulture so that if the code is running on a machine which uses different date separators or a different calendar, it won't make any difference.



来源:https://stackoverflow.com/questions/10854062/check-convert-from-a-string-to-date-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!