从文本字符串创建日期 - VB.Net

时间:2009-09-20 04:36:56

标签: vb.net datetime

我在将字符串转换为我需要的日期格式时遇到问题。我想要转换的字符串的一个示例是215056081909.我想将该字符串转换为08/19/09 21:50:56。

下面列出的代码是我尝试用于转换过程的代码。当我运行代码时,我收到下面的错误,我很确定这是因为我的字符串在军事(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)))

6 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

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

答案 2 :(得分:1)

如上所述,您的错误在于使用1-base而不是0-based索引。

请尝试以下索引......

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)))

答案 3 :(得分:1)

我认为您应该使用DateTime.TryParse,因为如果转换为日期失败,此函数不会抛出异常,它将返回true或false,具体取决于是否成功转换。

答案 4 :(得分:0)

为什么要通过“string-> convert”方法?使用long构造函数: http://msdn.microsoft.com/en-us/library/aa326687%28VS.71%29.aspx

如果需要,您可以解析各个部分并转换为整数,但它会更加明确并且应该更快,因为convert方法需要执行相同的解析方法。

答案 5 :(得分:0)

尝试DateTime.ParseExact(“215056081909”,“HHmmssMMddyy”)。ToString(“MM / dd / yy HH:mm:ss”)