VB.NET DateTime.Parse

DateTime

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 Format

Example

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.

Program that uses DateTime.Parse function: VB.NET

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
Programming tip

Default time. 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.

Example 2

String type

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.

Program that uses DateTime.Parse in examples: VB.NET

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 VB.NET programming language

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.


VB.NET: Time