How to Convert String to DateTime in VB.NET

How to Convert String to DateTime in VB.NET. In this Visual basic programming example, Let’s see How to Convert String to DateTime in VB.NET.

DateTime.Parse() in VB.NET

In .Net, you can work with date and time easily with the DateTime class. You can use the methods like Convert.ToDateTime(String), DateTime.Parse() and DateTime.ParseExact() methods for converting a string-based date to a System.DateTime object.

Convert.ToDateTime(String)

This method will convert the specified string representation of a date and time to an equivalent date and time value.

Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)
MsgBox(oDate.Day & " " & oDate.Month & "  " & oDate.Year)

DateTime.Parse()

DateTime.Parse method supports many formats. It is very forgiving in terms of syntax and will parse dates in many different formats. That means, this method can parse only strings consisting exactly of a date/time presentation, it cannot look for date/time among the text.

Dim iDate As String = "2005-05-05"
Dim oDate As DateTime = DateTime.Parse(iDate)
MsgBox(oDate.Day & " " & oDate.Month & "  " & oDate.Year)

DateTime.ParseExact()

ParseExact method will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. The format of the string representation must match the specified format exactly.

Dim iString As String = "2005-05-05 22:12 PM"
Dim oDate As DateTime = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt", Nothing)
MsgBox(oDate.ToString())

DateTime.TryParse method

DateTime.TryParse converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style and returns a value that indicates whether the conversion succeeded.

public static bool TryParse(
 string s,
 out DateTime result
)

This method is similar to the DateTime.Parse(String) method, except that the TryParse(String, DateTime) method does not throw an exception if the conversion fails. Also, this method tries to ignore unrecognized data, if possible, and fills in a missing month, day, and year information with the current date. The TryParse method is culture-dependent so be very careful if you decide to use it.

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

In this way, we learn How to Convert String to DateTime in VB.NET.