如何(尝试)将单个字符串解析为“DD/MM/YYYY”格式的日期时间?(VB.Net)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2794305/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:51:51  来源:igfitidea点击:

How to (try)parse a single String to DateTime in "DD/MM/YYYY" format? (VB.Net)

vb.netdatetimeparsingformattryparse

提问by lesderid

How to (try)parse a single String to DateTime in "DD/MM/YYYY" format? (VB.Net)

如何(尝试)将单个字符串解析为“DD/MM/YYYY”格式的日期时间?(VB.Net)

For example: I use input string "30/12/1999" (30 December 1999), how to (try)parse it to DateTime?

例如:我使用输入字符串“30/12/1999”(1999 年 12 月 30 日),如何(尝试)将其解析为 DateTime?

回答by Andrew Hare

Try this:

尝试这个:

Dim date As Datetime = DateTime.ParseExact(_
    yourString, "dd/MM/yyyy", CultureInfo.InvariantCulture)

This will throw an exception if yourStringdoes not match the format you specify. If you do not want an exception in this case then do this:

如果yourString与您指定的格式不匹配,这将引发异常。如果您不希望在这种情况下出现异常,请执行以下操作:

Dim date As Date    
Date.TryParseExact(dateString, "dd/MM/yyyy", CultureInfo.CurrentCulture, _
                      DateTimeStyles.None, date)