如何在 .NET 中比较独立于当前文化的日期
我在 .net 2.5 应用程序中硬编码了试用到期日期。如何将其与用户的系统日期进行比较,以便无论用户的文化设置如何,比较都是准确的?
DateTime maxTrialDate = DateTime.Parse("11/17/2020", new System.Globalization.CultureInfo("en-US"));
DateTime curDate = DateTime.Parse(DateTime.Now.ToShortDateString(), new System.Globalization.CultureInfo("en-US"));
//the next line of code uses the DateDiff method to compare the two dates -dont recall its //exact syntax.
在我的 XP 机器上,如果日期时间的控制面板区域设置为 en-US
,则上述代码有效,但如果我将其更改为 en-AU
,则上述代码设置curDate
引发 FormatException“日期的字符串格式不正确”
I hardcode a trial expiration date in my .net 2.5 app. how do I compare it with the user's system date such that the comparison is accurate regardless of the user's culture settings?
DateTime maxTrialDate = DateTime.Parse("11/17/2020", new System.Globalization.CultureInfo("en-US"));
DateTime curDate = DateTime.Parse(DateTime.Now.ToShortDateString(), new System.Globalization.CultureInfo("en-US"));
//the next line of code uses the DateDiff method to compare the two dates -dont recall its //exact syntax.
On my XP machine the above works if the control panel regional setting for datetime is en-US
, but if I change it to en-AU
, then the above code that sets curDate
fires a FormatException "Date is not in a correct string format"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您避免使用字符串来表示日期,则不会遇到此问题:
DateTime
是通过显式定义日、月和年组成部分创建的,因此区域设置不会造成混乱。If you avoid using strings to represent the dates, you will not encounter this problem:
The
DateTime
is created by explicitly defining the day, month and year components, so the regional settings will not confuse matters.只在各处使用
CultureInfo.InvariantCulture
怎么样?What about just using
CultureInfo.InvariantCulture
all over the place?您可以使用 System.Globalization.CultureInfo.InvariantCulture
You can use System.Globalization.CultureInfo.InvariantCulture
如果我没记错的话,在美国以外的大多数地方,标准日期格式是 dd/mm/yyyy,而不是美国标准的 mm/dd/yyyy。可能是在尝试解析日期时,它认为 17 是月份,这是一个无效的月份,从而导致错误。
If I remember correctly, in most places outside the US, the standard date format is dd/mm/yyyy, rather than the US standard of mm/dd/yyyy. It might be that when trying to parse the date, it believes the 17 is the month, which is an invalid month, thus causing the error.
如果您对到期日期进行硬编码,那么为什么要使用 Parse 方法,只需将其与
日期时间.now
Why are you using the Parse method if you are hardcoding expiration date just compare it to
DateTime.now
由于您明确要求解析器使用
en-US
,因此预计会出现FormatException
。尝试调用单参数重载
DateTime.Parse()
,或者,如果您确实想使用两个参数重载 (*cough*FxCop*cough*),如下所示:The
FormatException
is expected since you explicitly ask the parser to useen-US
.Try calling the one-argument overload of
DateTime.Parse()
, or alternatively, if you really want to use the two-args overload (*cough*FxCop*cough*), something like: