locked
Converting String to Datetime RRS feed

  • Question

  • User1122355199 posted

    Hello everyone and thanks for your help in advance.  I am working on an application that is required to parse a text file that returns a date and time, formatted in this fashion.  The date:

    20160501

    and the time:

    0512

    I want to parse and concatenate the two strings into one datetime.  I tried the following:

    TransactionSetDate = Microsoft.VisualBasic.Mid(TransactionSetDate, 5, 2) & "/" & Microsoft.VisualBasic.Right(TransactionSetDate, 2) & "/" & Microsoft.VisualBasic.Left(TransactionSetDate, 4)
    
    TransactionSetTime = Microsoft.VisualBasic.Left(TransactionSetTime, 2) & ":" & Microsoft.VisualBasic.Right(TransactionSetTime, 2)

    However, when I try converting these to a datetime:

    Dim TransactionDateString As datetime = TransactionSetDate & " " & TransactionSetTime

    I do not get a valid datetime.  I also tried using DateTime.ParseExact and Convert.ToDateTime without success.   Any help would be appreciated.

    Saturday, May 14, 2016 3:04 AM

Answers

  • User-369506445 posted

    hi

    please try below code :

     Dim sDate As String = "20160501"
            Dim sTime As String = "0512"
            Dim newDate As DateTime = DateTime.ParseExact(sDate & sTime,
                                      "yyyyMMddhhmm",
                                       CultureInfo.InvariantCulture)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, May 14, 2016 4:33 AM

All replies

  • User-369506445 posted

    hi

    please try below code :

     Dim sDate As String = "20160501"
            Dim sTime As String = "0512"
            Dim newDate As DateTime = DateTime.ParseExact(sDate & sTime,
                                      "yyyyMMddhhmm",
                                       CultureInfo.InvariantCulture)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, May 14, 2016 4:33 AM
  • User1122355199 posted

    Perfect.  Thanks for the help.

    Saturday, May 14, 2016 4:14 PM