Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET: How to convert string to Date?

Tags:

date

vb.net

I have string coming in through an SSIS package via text file in form:

"20090910" (string)

and it needs to be

2010-09-01 00:00:00 (Date)

Any suggestions?

like image 920
Matthew Avatar asked Dec 02 '10 18:12

Matthew


People also ask

What is CDate in VB net?

The CDate function converts a valid date and time expression to type Date, and returns the result. Tip: Use the IsDate function to determine if date can be converted to a date or time.

How do I change the Date format in Visual Basic?

You must enclose a Date literal within number signs ( # # ). You must specify the date value in the format M/d/yyyy, for example #5/31/1993# , or yyyy-MM-dd, for example #1993-5-31# . You can use slashes when specifying the year first.


1 Answers

Try DateTime.ParseExact()

Example from MSDN with your data:

Dim dateString, format As String  
Dim result As Date
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture

' Parse date and time with custom specifier.
dateString = "20090910"
format = "yyyyMMdd"        
Try
   result = Date.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
   Console.ReadLine()
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 
like image 182
p.campbell Avatar answered Oct 18 '22 18:10

p.campbell