DateTime 解析在 Windows 中不起作用 7: 该字符串未被识别为有效的 DateTime

DateTime parsing not working in Windows 7: The string was not recognized as a valid DateTime

在我开始解释之前,我需要告诉你我已经尝试了 Whosebug 中提供的所有可能的解决方案。但不适用于 windows 7.

On windows 7 解析日期时间不工作。 我尝试了以下代码片段

DateTime.ParseExact(arr[TransactionDateIndex], "M/dd/yyyy h:mm:ss tt", null);
DateTime.ParseExact(arr[TransactionDateIndex], "M/d/yyyy h:mm:ss tt",CultureInfo.InvariantCulture);
DateTime.Parse(DateTime.Parse(arr[TransactionDateIndex]).ToString("M/d/yyyy h:mm:ss tt"),CultureInfo.InvariantCulture);  

我有一个包含交易日期列的输入文件,它可以是任何有效的日期时间格式,现在在文件中它的 (MM/dd/YYYY) 我需要将其转换为 "M/d/yyyy h:mm:ss tt"格式。
当 运行 在 XP 中此代码工作正常但在 windows 7 中甚至在尝试 ParseExact 后它显示错误。
即使我使用

if (DateTime.TryParse(input, out dateTime))  
{
}

虽然 运行 在 windows 7 中,很少有记录会被视为无效,但在 XP 中会解析相同的内容。

如果您当前的日期时间格式是 MM/dd/yyyy 那么你应该使用 as

   string dateString = "02/15/2015"
   DateTime dateValue = DateTime.ParseExact(dateString , "MM/dd/yyyy", CultureInfo.InvariantCulture);

如果您想将其转换为您提到的其他格式 M/d/yyyy h:mm:ss tt,则可以将 .Tostring('M/d/yyyy h:mm:ss tt') 添加到日期。

再次阅读你的问题时,你提到它可以是任何有效的日期时间格式 如果是这样并且你的 cultureInfo 是固定的。

您可以使用类似下面的内容,但请注意,可能有不止一种格式可以解析相同的日期。例如,10/11/12 可以解析为 yyyy/MM/ddMM/dd/yyyy,它们都是有效的美国日期格式。 MM/dd/yyyy 更常见,因此它出现在列表的第一位,并且是下面代码返回的那个(如果您将它用于美国文化而不是示例中的文化)。

 string testValue = "02/15/2015";

 DateTime result; 
 CultureInfo ci = CultureInfo.GetCultureInfo("sl-SI"); 
 string[] fmts = ci.DateTimeFormat.GetAllDateTimePatterns();
 Console.WriteLine(String.Join("\r\n", fmts)); 
 if (DateTime.TryParseExact(testValue, fmts, ci,    DateTimeStyles.AssumeLocal, out result)) { 
      Console.WriteLine(result.ToLongDateString());   
 }

如果 CultureInfo 也未修复,那么您应该获取所有可用的反文化,然后从中获取所有格式,然后解析日期时间。

可能是

中存在无效日期
arr[TransactionDateIndex]

所以先尝试硬编码日期。然后您可以使用 debug.write() (windows app) 或 trance.write() (asp.net) 检查传递给 date.parse 的所有值,方法是使用 debug class in System.Diagnostics 并检查输出 window 是否有任何不一致的日期格式。

最后,您可以将此代码放在出现此代码的方法的顶部:

System.Threading.Thread.CurrentCulture = CultureInfo.InvariantCulture;