DateTimeTryParse with IFormatProvider culture information using c#

DateTimeTryParse with IFormatProvider culture information using c#

DateTime.TryParse accepts 2 overloaded methods. You need to specify the formatting culture information before processing date time validation. TrypParse method returns Boolean value.

DateTime.TryParseCulture IFormatProvider

C# DateTime.TryParse example using IFormatProvider

In this C# DateTime TryParse example we are passing culture information as IFormatProvider to TryParse method.

You can see difference in input string format and output string format. It is due to current culture is in en-US English US format and input date string is in English UK en-GB format. We have to tell culture information to TryParse method to get valid DateTime string from input date.

using System;
using System.Globalization;
namespace Csharp.DateTimeTryParse.Culture.Example
{
class Program
{
static void Main(string[] args)
{
string InputDate = "31/12/2012";
DateTime dt;
if (DateTime.TryParse(InputDate, new CultureInfo("en-GB"), DateTimeStyles.None, out dt))
Console.WriteLine("{0} Is valid DateTime", dt.ToString());
else
Console.WriteLine("{0} Is invalid DateTime", InputDate);
Console.ReadLine();
}
}
}
Output 12/31/2012 12:00:00 AM Is valid DateTime

VB.net DAteTime.TryParse example with culture information IFormatProvider

VB.net Program

Here VB.net example use IFormatProvider to Try parsing of input date. It also use culture information of date.

Imports System.Globalization
Namespace Csharp.DateTimeTryParse.Culture.Example
Class Program
Private Shared Sub Main(args As String())
Dim InputDate As String = "31/12/2012"
Dim dt As DateTime
If DateTime.TryParse(InputDate, New CultureInfo("en-GB"), DateTimeStyles.None, dt) Then
Console.WriteLine("{0} Is valid DateTime", dt.ToString())
Else
Console.WriteLine("{0} Is invalid DateTime", InputDate)
End If
Console.ReadLine()
End Sub
End Class
End Namespace
Output 12/31/2012 12:00:00 AM Is valid DateTime

Tags:

C# DateTimeIFormatProvider DateTime C#.netLong date using Culture InformationDateTimeTryParse using C# and VB.net exampleC# foreach loopc# arraylistc# stringC# DateTime DifferenceC# Parse method of DateTimeC# XML XmlReaderC# Binary To String

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.