DateTimeTryParse using C# and VB.net example
Here is C#.net DateTime Try Parse example. DateTime.TryParse has two overloaded methods. If input date time string is valid, DateTime.TryParse function returns Boolean true value and vice a versa. DateTime is passed to function using OUT keyword. We will also see VB.net example of DateTime.TryParse
C# DateTime.TryParse
C# program uses en-US as default culture of running thread. One date string is passed in en-US MM/DD/YYYY format and other is passed in English UK format as en-GB DD/MM/YYYY. As the current thread is en-US, output of second date string is invalid date format.
using System;
namespace Csharp.DateTimeTryParse.Example
{
class Program
{
static void Main(string[] args)
{
string firstInputDate = "12/31/2012";
string secondInputDate = "31/12/2012";
DateTime firstDateTime;
DateTime secondDateTime;
if (DateTime.TryParse(firstInputDate, out firstDateTime))
Console.WriteLine("{0} Is valid DateTime", firstDateTime.ToString());
else
Console.WriteLine("{0} Is invalid DateTime", firstDateTime.ToString());
if (DateTime.TryParse(secondInputDate, out secondDateTime))
Console.WriteLine("{0} Is valid DateTime", secondDateTime.ToString());
else
Console.WriteLine("{0} Is invalid DateTime", secondDateTime.ToString());
Console.ReadLine();
}
}
}
Output
12/31/2012 12:00:00 AM Is valid DateTime
1/1/0001 12:00:00 AM Is invalid DateTime
VB.net DateTime.TryParse example
VB.net Example uses DateTime.TryParse first overloaded method which accepts two parameter.
Namespace VBDotNet.DateTimeTryParse.Example
Class Program
Private Shared Sub Main(args As String())
Dim firstInputDate As String = "12/31/2012"
Dim secondInputDate As String = "31/12/2012"
Dim firstDateTime As DateTime
Dim secondDateTime As DateTime
If DateTime.TryParse(firstInputDate, firstDateTime) Then
Console.WriteLine("{0} Is valid DateTime", firstDateTime.ToString())
Else
Console.WriteLine("{0} Is invalid DateTime", firstDateTime.ToString())
End If
If DateTime.TryParse(secondInputDate, secondDateTime) Then
Console.WriteLine("{0} Is valid DateTime", secondDateTime.ToString())
Else
Console.WriteLine("{0} Is invalid DateTime", secondDateTime.ToString())
End If
Console.ReadLine()
End Sub
End Class
End Namespace
Output
12/31/2012 12:00:00 AM Is valid DateTime
1/1/0001 12:00:00 AM Is invalid DateTime
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5