VB.NET:如何将字符串转换为日期?

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

VB.NET: How to convert string to Date?

vb.netdate

提问by Matthew

I have string coming in through an SSIS package via text file in form:

我有字符串通过文本文件通过 SSIS 包传入:

"20090910" (string)

and it needs to be

它必须是

2010-09-01 00:00:00 (Date)

Any suggestions?

有什么建议?

回答by p.campbell

Try DateTime.ParseExact()

尝试 DateTime.ParseExact()

Example from MSDN with your data:

来自 MSDN 的示例与您的数据:

Dim dateString, format As String  
Dim result As Date
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture

' Parse date and time with custom specifier.
dateString = "20090910"
format = "yyyyMMdd"        
Try
   result = Date.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
   Console.ReadLine()
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try