[英]DateTime weird behaviour
我创建了一个C#WinForms应用程序。
在我的电脑上,以下工作:
DateTime.ParseExact("13/05/2012", "dd/mm/yyyy", null)
但这不是:
DateTime.Parse("13/05/2012")
在我客户的电脑上,它是相反的。 这有效:
DateTime.Parse("13/05/2012")
但这不是:
DateTime.ParseExact("13/05/2012", "dd/mm/yyyy", null)
错误说明:
String was not recognized as a valid DateTime.
没有设法在互联网上找到有关此问题的任何信息。 该程序使用.Net Framework 4,是一个x86应用程序。 我运行Windows 8 x64,客户端运行Windows 7 x64。
有没有人知道为什么会这样?
谢谢。
您在不同计算机上获得不同行为的原因是因为它们运行的是不同的文化。 尝试在两台计算机上运行这行代码,看看它是否输出了不同的东西:( ideone)
System.Console.WriteLine(CultureInfo.CurrentCulture);
输出(例子):
en-US
文化指定了许多东西,其中一个是日期分隔符。 如果您想要所有用户的一致行为,请尝试指定文化:( ideone)
CultureInfo cultureInfo = CultureInfo.InvariantCulture; // or whatever you prefer
DateTime dateTime = DateTime.ParseExact("13/05/2012", "dd/MM/yyyy", cultureInfo);
上面的代码假设您有以下using语句:
using System;
using System.Globalization;
小心; 在自定义日期和时间格式字符串中 , mm
说明符表示“分钟”,而不是“月”。 你需要使用MM
几个月。
DateTime.ParseExact("13/05/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.