DateTime.Parse
A String
contains a date or time. Characters indicate the month, day and year. We want to convert it into a DateTime
instance in VB.NET.
The DateTime.Parse
Function handles many different formats of String
dates. Many formats from the Internet can be parsed. The function is flexible and useful.
To begin, we use the DateTime.Parse
Function. You must pass a string
value as its argument. You can assign a DateTime
to its result.
Module Module1 Sub Main() Dim value As String = "2000-02-02" Dim time As DateTime = DateTime.Parse(value) Console.WriteLine(time) End Sub End Module2/2/2000 12:00:00 AM
TryParse
exampleIf a date format might be invalid, we should use the DateTime.TryParse
function in an If
-Statement. If the format is valid, we can use the parsed value.
Module Module1 Sub Main() Dim value As String = "invalid" Dim time As DateTime If DateTime.TryParse(value, time) Then ' Use time if valid. End If Console.WriteLine("DONE") End Sub End ModuleDONE
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.
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 Module1/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
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. It works on many formats.
The DateTime
type provides more options for programmatic use. The string
type is more useful for input and output such as writing to files.