Question

I have the following line of code in existing implementation

DateTime.TryParseExact(
    "15/11/2021 00:00:00", 
    "dd/MM/yyyy HH:mm:ss",
    null,
    DateTimeStyles.None,
    out maturityDate);

which returns false that means that the passed string couldn't be parsed. This was really surprising for me because the pattern here seems to be accurate. According to MSDN null value within the third parameter means that the current culture info will be used (I assume it's Thread.CurrentThread.CurrentCulture).

Thread.CurrentThread.CurrentCulture in the watch window is en-US, but the instance of culture info was altered somewhere in the code later (date time formatters or something else).

When I pass CultureInfo.InvariantCulture or new CultureInfo("en-US") everything is ok.

Could anyone please say what causes the failure of TryParseExact here when null is passed? The similar questions gave no clue to me.

Was it helpful?

Solution

If you pass null, the CurrentCulture will be used.

From the MSDN documentation for TryParseExact:

If provider is Nothing, the CultureInfo object that corresponds to the current culture is used.

This means that if the current culture is something that uses different date/time separators than in your string, the parse will fail.

OTHER TIPS

15/11/2021 is not a valid US date format. 11/15/2021 is. I think the culture you want is en-GB

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top