Convert string to DateTime format using InvariantCulture in C# and VB.Net

RiteshRaj
 
on Dec 30, 2020 10:24 PM
4630 Views

When I am using the MM/dd/yyyy date format on my pc It is successfully converted from string to date with invariant culture. bcz Invariant culture expect (MM/dd/yyyy) this format.(It is ok)

DateTime value = Convert.ToDateTime(dateTime_string_value, CultureInfo.InvariantCulture);

According to this It throws the exception when the pc date format is  dd/MM/yyyy.(It is ok)

The problem statement is why its accepting the yyyy/MM/dd format and not generating an exception like dd/MM/yyyy. If possible please share the url where reason is given. I have search a lot on internet. Plz help. Thanks in advance.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 31, 2020 02:07 AM

Hi RiteshRaj,

dd/MM/yyyy is not a valid date since dd will be interpreted as the month.

Try using TryParse and specifying the format using ParseExact explicitly.

C#

string date = "31/12/2020";
DateTime dt;
if (!DateTime.TryParse(date, out dt))
{
    dt = DateTime.ParseExact(date, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
}

VB.Net

Dim date As String = "31/12/2020"
Dim dt As DateTime
If Not DateTime.TryParse(date, dt) Then
    dt = DateTime.ParseExact(date, "dd/MM/yyyy", Globalization.CultureInfo.InvariantCulture)
End If

For Convert.ToDateTime Method refer below link.

Convert.ToDateTime Method