HomeSearch

VB.NET DateTime.Parse: Convert String to DateTime

Use the DateTime.Parse Function to convert a string to a DateTime Structure.

DateTime.Parse. A String contains a date or time. We want to convert it into a DateTime instance in VB.NET. The DateTime.Parse Function handles many different formats of String dates. It is flexible and useful.DateTime

First, this example uses the DateTime.Parse Function. You must pass a string value as its argument. Then, you can assign a DateTime to its result. This transforms the string into a value indicating the DateTime.

Here: You can see in this example that the year, month, and day were correctly parsed.

However: The time was left at zero (equivalent to 12 AM), because none was specified. When you don't specify a time it is left at 12 AM.

VB.NET program that uses DateTime.Parse function Module Module1 Sub Main() Dim value As String = "2000-02-02" Dim time As DateTime = DateTime.Parse(value) Console.WriteLine(time) End Sub End Module Output 2/2/2000 12:00:00 AM

Example 2. Next, we examine the DateTime.Parse function using a variety of input formats. For completeness, I searched the Internet to find different DateTime format strings, and then passed them to the DateTime.Parse function.

Note: This function appeared to work correctly on all of the input strings, which means it is fairly flexible.

VB.NET program that uses DateTime.Parse in examples Module Module1 Sub Main() ' Simple slash format Dim time As DateTime = DateTime.Parse("1/1/2000") Console.WriteLine(time) ' HTTP header time = DateTime.Parse("Fri, 27 Feb 2009 03:11:21 GMT") Console.WriteLine(time) ' From w3.org time = DateTime.Parse("2009/02/26 18:37:58") Console.WriteLine(time) ' From nytimes.com time = DateTime.Parse("Thursday, February 26, 2009") Console.WriteLine(time) ' From dotnetperls.com time = DateTime.Parse("February 26, 2009") Console.WriteLine(time) ' From ISO Standard 8601 for Dates time = DateTime.Parse("2002-02-10") Console.WriteLine(time) ' From Windows file system Created/Modified time = DateTime.Parse("2/21/2009 10:35 PM") Console.WriteLine(time) ' From Windows Date and Time panel time = DateTime.Parse("8:04:00 PM") Console.WriteLine(time) End Sub End Module Output 1/1/2000 12:00:00 AM 2/26/2009 8:11:21 PM 2/26/2009 6:37:58 PM 2/26/2009 12:00:00 AM 2/26/2009 12:00:00 AM 2/10/2002 12:00:00 AM 2/21/2009 10:35:00 PM 6/2/2010 8:04:00 PM

Summary. The DateTime.Parse function in the VB.NET language is useful in many programs where you want to convert a string into a DateTime instance. The DateTime type provides more options for programmatic use.

And: The string type is more useful for input and output such as writing to files.

Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.