[英]DateTime weird behaviour
I have created a C# WinForms application. 我创建了一个C#WinForms应用程序。
On my computer the following works: 在我的电脑上,以下工作:
DateTime.ParseExact("13/05/2012", "dd/mm/yyyy", null)
but this doesn't: 但这不是:
DateTime.Parse("13/05/2012")
On my client's computers it's reversed. 在我客户的电脑上,它是相反的。 This works:
这有效:
DateTime.Parse("13/05/2012")
but this doesn't: 但这不是:
DateTime.ParseExact("13/05/2012", "dd/mm/yyyy", null)
The error states: 错误说明:
String was not recognized as a valid DateTime.
Didn't manage to find any information on the internet about this problem. 没有设法在互联网上找到有关此问题的任何信息。 The program uses .Net Framework 4 and is a x86 application.
该程序使用.Net Framework 4,是一个x86应用程序。 I run Windows 8 x64, the client runs Windows 7 x64.
我运行Windows 8 x64,客户端运行Windows 7 x64。
Does anybody have a clue as to why this occurs? 有没有人知道为什么会这样?
Thanks. 谢谢。
The reason you are getting different behaviour on different computers is because they are running with different cultures. 您在不同计算机上获得不同行为的原因是因为它们运行的是不同的文化。 Try running this line of code on both computers to see if it outputs something different: (ideone)
尝试在两台计算机上运行这行代码,看看它是否输出了不同的东西:( ideone)
System.Console.WriteLine(CultureInfo.CurrentCulture);
Output (example): 输出(例子):
en-US
The culture specifies many things, one of which is the date separator. 文化指定了许多东西,其中一个是日期分隔符。 If you want consistent behaviour for all users, try specifying a culture: (ideone)
如果您想要所有用户的一致行为,请尝试指定文化:( ideone)
CultureInfo cultureInfo = CultureInfo.InvariantCulture; // or whatever you prefer
DateTime dateTime = DateTime.ParseExact("13/05/2012", "dd/MM/yyyy", cultureInfo);
The above code assumes you have these using statements: 上面的代码假设您有以下using语句:
using System;
using System.Globalization;
Be careful; 小心; in custom date and time format strings , the
mm
specifier represents “minutes”, not “months”. 在自定义日期和时间格式字符串中 ,
mm
说明符表示“分钟”,而不是“月”。 You need to use MM
for months. 你需要使用
MM
几个月。
DateTime.ParseExact("13/05/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.