DateTime.TryParse
Sometimes in our VB.NET programs all our data is known to be valid, but more often, some is invalid. With DateTimes
, TryParse
helps us handle invalid data.
By returning True or False depending on whether the string
was parsed, we can quickly test for invalid data. We can only proceed if the parsing was completed.
Here we test the DateTime.TryParse
function in 2 different ways. We handle both a valid date string
, and a invalid one.
string
we parse. We initialize the DateTime
(date1) to MinValue
to avoid a warning in VB.NET.string
. The Else branch is reached, and the word Invalid is printed.Module Module1 Sub Main() ' Part 1: use DateTime.TryParse when input is valid. Dim input as String = "2022-02-02" Dim date1 = DateTime.MinValue If DateTime.TryParse(input, date1) Console.WriteLine(date1) End If ' Part 2: use DateTime.TryParse on invalid input. Dim badInput as String = "???" Dim date2 = DateTime.MinValue If DateTime.TryParse(badInput, date2) Console.WriteLine(date2) Else Console.WriteLine("Invalid") End If End Sub End Module2/2/2022 12:00:00 AM Invalid
TryParseExact
Suppose we have a format string
that we know the date string
will adhere to. We can specify the format with letters such as "d" and "y."
System.Globalization
namespace so that we have access to the CultureInfo
type.string
, and the format string
that tells TryParseExact
how to parse the string
.TryParseExact
with the required arguments—these can be changed for more precise control of the method.imports System.Globalization Module Module1 Sub Main() Dim dateString as String = "Mon 16 Jun 8:30 AM 2008" Dim format as String = "ddd dd MMM h:mm tt yyyy" Dim dateTime as DateTime = DateTime.MinValue ' Use TryParseExact to handle the date with a format string. If DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, dateTime) Console.WriteLine(dateTime) End If End Sub End Module6/16/2008 8:30:00 AM
Though parsing strings into DateTimes
is not always easy, TryParse
and TryParseExact
can often be helpful. Usually, TryParse
is sufficient for this purpose.