Nuthan Gowda Nuthan Gowda - 3 days ago 7
C# Question

DateTime.TryParse() issue while converting German date to US date

Currently I'm having hard time finding how to resolve my problem related to the DateTime.TryPase function

String formattedDateString = String.Empty;

// German date dd.mm.yyyy
string dateString = "14.03.2016";
DateTimeFormatInfo dateTimeFormat = null;

//automatically throws and exception if the locale is not in the correct format
CultureInfo fromCulture = new CultureInfo("en-US");
DateTime tryParseDateTime;


//automatically throws and exception if the locale is not in the correct format
CultureInfo toCulture = new CultureInfo("de-de");
dateTimeFormat = toCulture.DateTimeFormat;

// expecting result to fail
if (DateTime.TryParse(dateString, fromCulture, DateTimeStyles.None, out tryParseDateTime))
{
formattedDateString = tryParseDateTime.ToString("d", dateTimeFormat);
Console.WriteLine("success");
}
else
{
Console.WriteLine("Failed");
}


So here in my Code, I'm sending German format date i.e dd.mm.yyyy and expecting the DateTime.TryParse to fail but since the day is below 12, it assumes that has month and returns the success statement.

If I pass the German date "15.03.2016" this works fine.

How can I resolve my problem here.

Here the requested locale is German

Thanks

Answer

Note: The questioner expects the conversion to fail. He only wants the conversion to succeed when the input string is NOT in the German format but in the US format.


Use DateTime.TryParseExact and pass in the expected format from your source culture.

    // German date dd.mm.yyyy
    string dateString = "01.03.2016";

    CultureInfo fromCulture = new CultureInfo("en-US");
    DateTime tryParseDateTime;

    // expecting result to fail
    if (DateTime.TryParseExact(dateString, fromCulture.DateTimeFormat.ShortDatePattern, fromCulture, DateTimeStyles.None, out tryParseDateTime))
    {
        MessageBox.Show("Success");
    }
    else
    {
        MessageBox.Show("Failed");
    }
Comments