简体   繁体   English

检查并从字符串转换为日期vb.net

[英]check & convert from a string to date vb.net

I am a beginner in VB.NET & I am stuck at a very simple thing, Date formats. 我是VB.NET的初学者,我陷入了一个非常简单的事情,日期格式。

I am working on an application which uploads data from excel sheets into sql server database. 我正在开发一个应用程序,它将excel表中的数据上传到sql server数据库。 The application will accept dates only if they are in mm/dd/yyyy format. 只有在mm / dd / yyyy格式下,应用程序才会接受日期。 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. 请帮忙。

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: 使用DateTime.TryParseExact ,它允许您指定格式 - 它将尝试解析它,在成功时将解析的值放入输出参数,并返回成功/失败:

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. 显然,如果需要,可以添加Else子句等。

(I believe in modern VB the line continuations may be unnecessary, but hey... hopefully you get the point.) (我相信在现代VB中,线路延续可能是不必要的,但是嘿......希望你能明白这一点。)

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. 请注意,我已明确使用CultureInfo.InvariantCulture因此如果代码在使用不同日期分隔符或不同日历的计算机上运行,​​则不会产生任何差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM