2009-09-20 21 views
1

我有问题将字符串转换为我需要的日期格式。我试图转换的字符串的一个例子是215056081909.我想将该字符串转换为08/19/09 21:50:56。从文本字符串创建日期 - VB.Net

下面列出的代码是我试图用于转换过程。当我运行代码时,我得到下面的错误,我很确定这是因为我的字符串在军事(24小时)时间中有时间部分。任何人都可以帮我把字符串转换成我需要的格式吗?

谢谢!

Error: 
System.ArgumentOutOfRangeException was unhandled 
     Message="Index and length must refer to a location within the string. Parameter name: length" 
     ParamName="length" 
     Source="mscorlib" 
     StackTrace: 
      at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) 
      at System.String.Substring(Int32 startIndex, Int32 length) 
      at GLTracker.PortManager.DoDataCollection(MessageType type, String msg) 
      at GLTracker.PortManager.comPort_DataReceived(Object sender, SerialDataReceivedEventArgs e) 
      at System.IO.Ports.SerialPort.CatchReceivedEvents(Object src, SerialDataReceivedEventArgs e) 
      at System.IO.Ports.SerialStream.EventLoopRunner.CallReceiveEvents(Object state) 
      at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state) 
      at System.Threading.ExecutionContext.runTryCode(Object userData) 
      at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) 
      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) 
      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
      at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack) 
      at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state) 
     InnerException: 




'Code: 
Dim strDateTime as string = "215056081909" 

Dim dTransDate As DateTime = Convert.ToDateTime(String.Format("{0}/{1}/{2} {3}:{4}:{5}", _ 
                   strDateTime.Substring(7, 2), _ 
                   strDateTime.Substring(9, 2), _ 
                   strDateTime.Substring(11, 2), _ 
                   strDateTime.Substring(0, 2), _ 
                   strDateTime.Substring(3, 2), _ 
                   strDateTime.Substring(5, 2))) 

回答

7

既然你有一个确切的格式,您可以使用DateTime.ParseExact提供的格式和输入数据,以试图将日期转换:

Dim theDate As DateTime = DateTime.ParseExact("215056081909", _ 
               "HHmmssMMddyy", _ 
               CultureInfo.CurrentCulture) 

您不妨考虑在情况下,使用DateTime.TryParseExact输入被潜在畸形:

Dim theDate As DateTime 
If DateTime.TryParseExact("215056081909", _ 
          "HHmmssMMddyy", _ 
          CultureInfo.CurrentCulture, _ 
          DateTimeStyles.None, _ 
          theDate)) Then 
    ' Parsing succeeded, and theDate will contain the parsed date 
End If 
+0

这工作很棒...谢谢。 – 2009-09-20 06:05:23

3

我相信VB.NET字符串是基于0的。您最右边的子字符串从11开始,长度为2. 11 + 2 == 13

+0

你是对的,这是我使用的语法的主要问题。 谢谢! – 2009-09-20 06:07:54

0

为什么要通过“字符串 - >转换”方法?使用长构造: http://msdn.microsoft.com/en-us/library/aa326687%28VS.71%29.aspx

您可以分析出各个部分,如果你想转换为整数,但它会更加明确,应该是更快,因为转换方法需要做同样的解析方法。

+0

我尝试过,但无法使用每个必需变量的strDateTime.substring(10,2)语法来使用它。继续得到一个错误:重载解析失败,因为没有可访问的'New'可以用这些参数调用: – 2009-09-20 06:13:56

1

如上所述,您的错误是使用1位而不是基于0的索引。

试试下面的指标,而不是...

Dim dTransDate As DateTime = _ 
    Convert.ToDateTime(String.Format("{0}/{1}/{2} {3}:{4}:{5}", _ 
     strDateTime.Substring(6, 2), _ 
     strDateTime.Substring(8, 2), _ 
     strDateTime.Substring(10, 2), _ 
     strDateTime.Substring(0, 2), _ 
     strDateTime.Substring(2, 2), _ 
     strDateTime.Substring(4, 2))) 
+0

是的,正如L. Moser说的,你的例子显示...我没有正确设置索引。 感谢您的帮助! – 2009-09-20 06:15:47

+0

我不确定我是否应该发布这个单独的问题...如果我应该让我知道,我会这样做。 我把这个日期作为需要快速解析并保存到数据库表的条码的一部分来抓取。在列出的三种方法中,哪些是首选(最快)方法? – 2009-09-20 06:23:02

+0

这可能应该是一个单独的问题,因为它是一个不同的问题。一个是“为什么不是这个代码工作”,另一个是“什么是最好的方式做”,他们会有不同的答案。 – eidylon 2009-09-21 06:19:10

0

尝试DateTime.ParseExact( “215056081909”, “HHmmssMMddyy”)的ToString( “MM/DD/YY HH:MM:SS”)

1

我认为你应该使用DateTime.TryParse因为这功能如果转换日期失败,不会抛出异常,它将根据转换是否成功返回true或false。