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

6

我通过文本文件以以下形式收到字符串,这是通过SSIS包传输的:

"20090910" (string)

它需要被这样做。

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

任何建议?
1个回答

11

尝试使用DateTime.ParseExact()

使用你的数据,以下是来自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 

它似乎不喜欢这个。SSIS 给出非常晦涩的错误,我无法在脚本组件中逐步执行代码。 - Matthew
字符串“2”无法转换为类型“Double”。 - Matthew
我导入了 System.Globalization。 - Matthew
请问您能否编辑您的帖子,包含 SSIS 给您的完整错误信息吗?需要提供堆栈跟踪和所有相关信息。最重要的是错误报告的行号,以及对应行号上的语句。似乎错误与日期时间解析无关,但目前还不清楚。 - p.campbell
啊,看来我解决了这个问题。字符串“2009…”周围有引号,所以我使用了string.replace将它们去掉,现在它可以工作了。很抱歉浪费了你的时间。 - Matthew
您可能希望使用TryParseExact来避免任何异常,如果字符串未按您的预期格式输入。 - Chris Dunaway

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接