DateTime.ParseExact 格式异常:字符串无法识别为有效的日期时间

9
我对这个问题完全不知所措。据我所见,文档和我在SO上看到的其他帖子都说这应该可行。我一定是错过了一些愚蠢的东西,但我就是看不到它。
以下代码行会导致"字符串未被识别为有效的DateTime"的FormatException异常:
return DateTime.ParseExact(value, DateFormat, null,
                           DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal);
  • value的值为"11/04/2013"
  • DateFormat"dd/MM/yyyy"
  • 当前区域设置为en-GB
  • 我尝试了各种不同的DateTimeStyles变体,但都没有效果。

我的初衷是使用格式ddd, dd/MMM/yyyy,但那也不起作用(在那种情况下的值为Tue, 30/Apr/2013

我还尝试通过传递new CultureInfo("en-GB")而不是null来强制使用en-GB区域设置。

我还将代码提取到自己的控制台应用程序中,以查看环境是否有所不同(ASP.NET MVC 3)。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var DateFormat = "dd/MM/yyyy";
            var value = "30/04/2013";
            var culture = new CultureInfo("en-GB");
            var result = DateTime.ParseExact(value, DateFormat, culture,
                           DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal);
            Console.WriteLine("\"{0}\" as \"{1}\" ==> {2}", value, DateFormat, result);
            Console.ReadKey();
        }
    }
}

这仍然给我同样的错误。


2
控制台应用程序对我有效。我的机器上默认文化是“de-DE”。 - Daniel Hilgarth
我的两个同事说它对他们也有效。但我的电脑并不这样认为。也许我的安装已经损坏了。不确定是怎么回事——其他代码都能正常运行。 - Colin Mackay
2
在您的计算机上,Thread.CurrentThread.CurrentCultureThread.CurrentThread.CurrentUICulture 的值是什么? - Daniel Hilgarth
尝试将CultureInfo.InvariantCulture传递给ParseExact,看看是否有效。 - vidario
2个回答

12

这个管用吗

 string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh:mm:ss:tt", 
                                           CultureInfo.InvariantCulture)

设置不变文化已经生效了。不知道为什么,但它起作用了。 - Colin Mackay

7
string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy HH:mm:ss:tt",  
                                           CultureInfo.InvariantCulture);

请注意使用了HH(24小时制)而不是hh(12小时制),并且使用InvariantCulture,因为有些文化使用除斜杠之外的分隔符。
例如,如果文化是de-DE,则格式“dd/MM/yyyy”将期望使用句点作为分隔符(31.01.2011)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接