vb.net 如何使用 Date.TryParseExact 将字符串解析为日期

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

How to Parse String to Date Using Date.TryParseExact

.netvb.netparsingdate

提问by r.r

reading
Dim lendingtimedate As String = If(irequest.Form.Contains("startingtimedate"), irequest.Form("endingtimedate").Value, "")


Dim lendingtimedate As String = If(irequest.Form.Contains("startingtimedate"), irequest.Form("endingtimedate").Value, "")

getting value : lendingtimedate = "04/23/2014 12:45 PM"

获得价值: lendingtimedate = "04/23/2014 12:45 PM"

and now i will to parse it in

现在我将解析它

Dim edateValue As Date

as

作为

Dim enddate = Date.TryParseExact(lendingtimedate, "MM/dd/yyyy h:mm:ss tt", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, edateValue)

but enddate is always: edateValue = #12:00:00 AM#

但结束日期总是: edateValue = #12:00:00 AM#

please help me to find out why i cant get

请帮我找出为什么我不能得到

edateValue = "04/23/2014 12:45 PM"

回答by Matt Wilko

TryParseExactreturns a Booleanindicating whether the parse succeeded or not, so you need to test for the result.

TryParseExact返回一个Boolean指示是否解析成功,因此您需要测试结果。

In your case it is returning False because your format string did not match the format of the string you are trying to parse (you have an extra :ssthat is not required).

在您的情况下,它返回 False 因为您的格式字符串与您尝试解析的字符串的格式不匹配(您有一个:ss不需要的额外字符串)。

The following code parses correctly:

以下代码正确解析:

Dim lendingtimedate = "04/23/2014 12:45 PM"
Dim edateValue As Date

If Date.TryParseExact(lendingtimedate, "MM/dd/yyyy h:mm tt", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, edateValue) Then
    Debug.WriteLine(edateValue)
Else
    Debug.WriteLine("Failed to parse")
End If

回答by Tim Schmelter

Because there are no seconds in "04/23/2014 12:45 PM", so this does not work:

因为没有秒"04/23/2014 12:45 PM",所以这不起作用:

"MM/dd/yyyy h:mm:ss tt"

but this:

但是这个:

"MM/dd/yyyy h:mm tt"