0

When a user is viewing the content in french I set the culture like:

Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-CA");

And when in english I set it as:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");

Now dates are stored in en-CA format so I explicity always format using:

var dateFormatPattern = "M/d/yyyy"; // "MM/dd/yyyy"

var dt = DateTime.MinValue;
if (DateTime.TryParseExact(dateString, dateFormatPattern, null, System.Globalization.DateTimeStyles.None, out dtResult))
{
    dt = dtResult;
}

Now it works in english, but when in french mode, the parse fails.

When in debug mode, I can see the value of dateString is the same in both french and english, but could it be the IDE changing the format? Since it is a string value, I don't think it could.

Then why is it failing?

4

1 回答 1

2

法国文化的日期分隔符是破折号。将格式字符串传递给 时,格式字符串中TryParseExact的任何斜杠都必须与输入日期中的日期分隔符匹配。

这意味着在使用格式M/d/yyyy和法国文化进行解析时,您需要提供一个带有格式的字符串M-d-yyyy才能成功解析。英语文化的日期分隔符是斜线,所以你看不到任何问题。

正确的解决方法取决于输入的来源以及您希望的宽松程度(例如,如果用户正在查看法语内容但提供了用斜杠格式化的日期怎么办?)。

于 2013-02-13T22:36:11.110 回答