Home
VB.NET
DateTime.TryParse Examples
This page was last reviewed on Nov 2, 2023.
Dot Net Perls
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.
DateTime.Parse
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.
Example. Here we test the DateTime.TryParse function in 2 different ways. We handle both a valid date string, and a invalid one.
Part 1 Here is the valid date string we parse. We initialize the DateTime (date1) to MinValue to avoid a warning in VB.NET.
Part 2 We handle an invalid date string. The Else branch is reached, and the word Invalid is printed.
If
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 Module
2/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."
Info We import the System.Globalization namespace so that we have access to the CultureInfo type.
Next We specify the date string, and the format string that tells TryParseExact how to parse the string.
Finally We invoke 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 Module
6/16/2008 8:30:00 AM
Summary. Though parsing strings into DateTimes is not always easy, TryParse and TryParseExact can often be helpful. Usually, TryParse is sufficient for this purpose.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 2, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.