如何删除System.Threading.Thread.CurrentThread.CurrentCulture上的DateTime.Parse依赖项

Pau*_*rth 2 .net c# datetime

请考虑以下代码:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fo-FO");
            var s = DateTime.MaxValue.ToString("yyyy-MM-ddTHH:mm:ssZ");
            var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
            Console.WriteLine("Was able to parse with fo-FO");
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e);
        }

        try
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            var s = DateTime.MaxValue.ToString("yyyy-MM-ddTHH:mm:ssZ");
            var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
            Console.WriteLine("Was able to parse with en-US");
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
   at System.DateTime.Parse(String s, IFormatProvider provider)
   at DateTimeTest2.Program.Main(String[] args) in C:\Projects\DateTimeTest2\DateTimeTest2\Program.cs:line 17
Was able to parse with en-US
Run Code Online (Sandbox Code Playgroud)

此代码片段证明DateTime.Parse使用Thread.CurrentThread.CurrentCulture,而不管传入"InvariantCulture"的事实.我发现这非常不直观,我认为这是一个"bug".

如果在任何情况下它实际上被DateTime.Parse忽略,为什么我们必须传入CultureInfo?有没有办法以独立于CurrentCulture的方式调用DateTime.Parse?

Aak*_*shM 9

此代码片段证明DateTime.Parse使用Thread.CurrentThread.CurrentCulture,而不管传入"InvariantCulture"的事实

我不确定这个例子是如何证明的.传递给的字符串DateTime.Parse是不同的,所以不同的结果随之而来并不奇怪.

第一个字符串的格式为时间23.59.59,显然InvariantCulture不能解析; 第二个字符串的格式为23:59:59,InvariantCulture 可以解析.有什么问题?

编辑添加,因为显然它有所不同,我运行.NET 2.0和分别由fo-FO和生成的字符串en-US

9999-12-31T23.59.59Z
Run Code Online (Sandbox Code Playgroud)

9999-12-31T23:59:59Z
Run Code Online (Sandbox Code Playgroud)