Home > Net >  take a string and turn it into a date
take a string and turn it into a date

Time:02-03

I am needing to take a string like 20230131 and turn it into 2023/01/31 then eventually reformat that into DD/MM/YR format. I am reading this from a txt file through stream reader and having to write it to a new file in different format using stream writer.

Using Visual Basic

Dim Start As String
Dim FileData()
FileData = myReader.ReadFiles()
Start = FileData(2)
myWriter.WriteLine("A004 " & Start)

I have tried start = Format(FileData(2), "####/##/##") But it keeps writing only #'s instead of the actual value.

CodePudding user response:

Since the string is a date, it would be easier to convert it to a DateTime type. Here is how you can parse the string into a DateTime:

Dim NewDate As DateTime = DateTime.ParseExact(Start, "yyyyMMdd")

From there, you can format the DateTime however you want. The .NET framework provides an overloaded method on the DateTime type called ToString(). The method allows you to pass in a string for the format (and culture-specific options if desired). Here is an example of that:

NewDate.ToString("yyyy/MM/dd")

Here is a link to the method's documentation on Microsoft Learn: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=net-7.0

CodePudding user response:

Dim Start As String
Dim FileData()
Dim NewStartDate As DateTime
Dim NewStartTime As DateTime
Dim NewFinishDate As DateTime
Dim NewFinishTime As DateTime
FileData = myReader.ReadFiles()
StartDate = FileData(2)
FinishDate = FileData (4)
FinishT = FileData(5)

NewStartDate = DateTime.ParseExact(StartDate, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture)
NewStartDate = NewStartDate.ToString(dd/MM/yyyy")
NewStartTime = DateTime.ParseExact(StartDate, "hhmmss", System.Globalization.CultureInfo.CurrentCulture)
NewStartTime = NewStartTime.ToString(hh:mm:ss")
NewFinishDate = DateTime.ParseExact(StartDate, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture)
NewFinishDate = NewFinishDate.ToString(dd/MM/yyyy")
NewFinishTime = DateTime.ParseExact(StartDate, "hhmmss", System.Globalization.CultureInfo.CurrentCulture)
NewFinishTime = NewFinishTime.ToString(hh:mm:ss")
myWriter.WriteLine("A004 " & NewStartDate & " " & NewFinishDate & " " & NewFinishTime)

This gives the correct format and works perfect. However, I am needing to add a end time and a end date when I do it tells me that conversion from string "14/12/2022" to type 'Date' is not valid. How can I now add the other end date and time.

  • Related