Interpreting dates: Console.Writeline vs. string.Format

為{幸葍}努か 提交于 2019-12-05 07:24:19

This situation arises because when MSTest redirects console output to the test window, it passes CultureInfo.InvariantCulture to the TextWriter associated with the console.

You can verify this with the following:

var threadCulture = Thread.CurrentThread.CurrentCulture;
var consoleCulture = Console.Out.FormatProvider;

Console.WriteLine(threadCulture.Equals(CultureInfo.InvariantCulture));
Console.WriteLine(consoleCulture.Equals(CultureInfo.InvariantCulture));

Unless you change it, the thread's current culture is usually something like en-US, or whatever your computer is set to. So the first item will usually be false.

But the second item varies depending on where it's run from. As a console application, the console output culture should default to the current thread culture - so it will be false. In XUnit or NUnit tests, the result is also false. But in MSTest, the result is true.

If you dig through the .NET Framework Reference Source, you'll see that

I don't think the sources for the MSTest test runner are publicly available, but one can conclude that they must somewhere do something like:

Console.Out = new SomeWriter(CultureInfo.InvariantCulture);

Where SomeWriter creates the test output and inherits from TextWriter.

On the other hand, String.Format will always use the thread's current culture, unless you specifically provide a different culture.

One way to work around this would be to explicitly set the thread's current culture to the invariant culture.

Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

This is due to how the Format method interpreters the / symbol.

From MSDN

If a custom format string includes the "/" format specifier, the DateTime.ToString method displays the value of DateSeparator in place of the "/" in the result string.

The DateSeparator property defines the string that replaces the date separator ("/" custom date and time format specifier) in a result string in a formatting operation. It also defines the date separator string in a parsing operation.

When you are changing the format, the default symbol is changed to space character.

If you need to display the / character, it can be escaped by using \. Thus changing the format string to {0:MM\/dd\/yy} will always display /.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!