开发者

How to compare dates independent of current culture in .NET

开发者 https://www.devze.com 2023-01-20 08:05 出处:网络
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?

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.Globaliz开发者_高级运维ation.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"


If you avoid using strings to represent the dates, you will not encounter this problem:

DateTime maxTrialDate = new DateTime(2020, 11, 17);

if (DateTime.Now.Date > maxTrialDate)
{
     // expired
}

The DateTime is created by explicitly defining the day, month and year components, so the regional settings will not confuse matters.


What about just using CultureInfo.InvariantCulture all over the place?


You can use System.Globalization.CultureInfo.InvariantCulture


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.


Why are you using the Parse method if you are hardcoding expiration date just compare it to DateTime.now


The FormatException is expected since you explicitly ask the parser to use en-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:

using System.Globalization;

DateTime.Parse("11/17/2020", CultureInfo.CurrentCulture);
0

精彩评论

暂无评论...
验证码 换一张
取 消