views:

282

answers:

6

I having a problem converting a string into the date format I need. An example of the string I'm trying to convert would be 215056081909. I would like to convert that string into 08/19/09 21:50:56.

The code listed below is what I'm trying to use for the conversion process. When I run the code I'm getting the error below and I'm pretty sure it's because my string has the time portion in military (24 hour) time. Could anyone help me get the string converted to the format I need?

Thank you!

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)))
+3  A: 

I believe VB.NET strings are 0-based. Your furthest right substring starts at 11 and has length of 2. 11+2 == 13

L. Moser
You are correct and this was the main issue with the syntax I was using.Thanks!
dc
A: 

Why go through the "string->convert" method? Use the long constructor: http://msdn.microsoft.com/en-us/library/aa326687%28VS.71%29.aspx

You can parse out the individual parts and convert to an integer if you want, but it'll be much more explicit and should be quicker, since the convert method needs to do the same parse methods.

Erich
I tried this but could not get it to work using the strDateTime.substring(10,2) syntax for each of the required variables. Keep getting an error: Overload resolution failed because no accessible 'New' can be called with these arguments:
dc
+1  A: 

As above, your error is in using 1-base instead of 0-based indices.

Try the following indexes instead...

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)))
eidylon
Yes as L. Moser stated and your example showed ...I was not setting the index correctly.Thanks for the help!
dc
I'm not sure if I should post this a separate question...If I should just let me know and I will do so.I'm grabbing this date as part of a bar code that needs to be quickly parsed and saved to a db table. Of the three methods listed what would be the preferred (quickest?) way to go about this?
dc
It probably should be a separate question, as it is a different problem. One was "why isn't this code working", the other is "what's the best way to do <this>", and they will have different answers.
eidylon
+6  A: 

Why not just do it like this?

Dim theDate As DateTime = DateTime.ParseExact("215056081909", "HHmmssMMddyy", CultureInfo.CurrentCulture)
Cory Larson
THis works great...Thank you.
dc
You're welcome :)
Cory Larson
A: 

Try DateTime.ParseExact("215056081909", "HHmmssMMddyy").ToString("MM/dd/yy HH:mm:ss")

CodeByMoonlight
+1  A: 

I think you should use the DateTime.TryParse as this function will not throw exception if the conversion to the date is failed, it will return true or false depending of whether converted successfully or not .

Asim Sajjad