} catch { 抛出新例外(有效日期失败); } } 其他 抛出新的例外(有效日期失败); } } } static void TestHardCoded() { for(int i = 0; i< Iterations; i ++) { foreach(字符串x无效) { if(IsProbablyValidDate(x)) { 试试 { DateTime.ParseExact(x," dd / mm / yyyy", CultureInfo.InvariantCulture); 抛出新的异常(无效的日期传递); } catch { } } } foreach(字符串x有效) { if(IsProbablyValidDate(x)) { 试试 { DateTime.ParseExact(x," dd / mm / yyyy", CultureInfo.InvariantCulture); } catch { 抛出新例外(有效日期失败); } } 其他 抛出新例外(有效日期失败); } } } static void TestNoPreCheck() { for(int i = 0;我<迭代; i ++) { foreach(字符串x无效) { 尝试 { DateTime.ParseExact(x," dd / mm / yyyy", CultureInfo.InvariantCulture); 抛出新的异常(无效的日期已过去); } catch { } } foreach(字符串x有效) { 尝试 { DateTime.ParseExact(x," dd / mm / yyyy", CultureInfo.InvariantCulture); } catch { 抛出新例外(有效日期失败); } } } } 静态readonly char [] LowerBounds =" 00/00/1000" .ToCharArray(); static readonly char [] UpperBounds =" 19/39/2999" .ToCharArray(); static bool IsProbablyValidDate(字符串日期) { if(date.Length!= 10) { 返回false; } for(int i = 0;我< date.Length; i ++) { char c = date [i]; if(c< LowerBounds [i] || c> UpperBounds [i]) { 返回false; } } 返回true; } } 笔记本电脑上的结果是: TestRegex: 00:00:09.3437500 TestHard编码:00:00:04.3437500 TestNoPreCheck:00:00:12.5156250 更改正则表达式 需要两个数字而不是1或2个月和白天加速非常小,但实际上并不是很好。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复该群组,请不要给我发邮件 你好Dan, 可能你正在使用C#,因为你写得很好你的DateTme.Parse()。 但是当你使用VBNet时你可以使用它。 http://msdn.microsoft.com/library/de...afctisdate.asp Cor 我的应用程序要求用户以mm / dd / yyyy 格式输入日期。有没有快速简便的方法来验证用户输入的日期 格式正确?现在我正在调用DateTime.Parse()并且在FormatException中捕获 但似乎这有点效率低 - 捕获 异常。有一些非常明显的延迟,它会追溯到调用堆栈中的。有没有更好的办法?返回bool的东西 可能吗? My application asks the user to enter in a date - in the mm/dd/yyyy format. Is there any quick and easy way to verify the date the user enters is formatted correctly? Right now I''m calling DateTime.Parse() and catching the FormatException but it seems this is a bit inefficient - catching the exception that is. There is some pretty obvious delay while it traces back up the call stack. Is there a better way? Something that returns a bool possibly?--Dan S 解决方案 Hi,To just check the format you may use regular expressions like\d{1,2}\/\d{1,2}\/\d{4}. If this validates, use DateTime.Parse() to checkthe actual values."Dan S" <Da**@discussions.microsoft.com> wrote in messagenews:2B**********************************@microsof t.com...My application asks the user to enter in a date - in the mm/dd/yyyy format.Is there any quick and easy way to verify the date the user enters isformatted correctly? Right now I''m calling DateTime.Parse() and catchingthe FormatException but it seems this is a bit inefficient - catching theexception that is. There is some pretty obvious delay while it traces backup the call stack. Is there a better way? Something that returns a boolpossibly?--Dan SDan S <Da**@discussions.microsoft.com> wrote: My application asks the user to enter in a date - in the mm/dd/yyyy format. Is there any quick and easy way to verify the date the user enters is formatted correctly? Right now I''m calling DateTime.Parse() and catching the FormatException but it seems this is a bit inefficient - catching the exception that is. There is some pretty obvious delay while it traces back up the call stack. Is there a better way? Something that returns a bool possibly?After the first time, which may involve a delay due to loadingresources, throwing an exception is likely to be very fast - far fasterthan a user can actually notice. On my laptop I can throw a hundredthousand exceptions in a second - I think that''s rather more than auser is likely to enter.I''m not saying that exceptions are always a nice way to go, but Iwouldn''t dismiss them for performance reasons - at least not in thiscase.You can use a regular expression to check the format, of course - butyou may well find that doing so is more expensive than just trying toparse the date and catching the exception.You could probably do slightly better with a hard-coded test, somethinglike:static readonly char[] LowerBounds = "00/00/1000".ToCharArray();static readonly char[] UpperBounds = "19/39/2999".ToCharArray();static bool IsProbablyValidDate(string date){if (date.Length != 10){return false;}for (int i=0; i < date.Length; i++){char c=date[i];if (c < LowerBounds[i] || c > UpperBounds[i]){return false;}}return true;}That gets rid of *many* invalid dates, but not all - you''ll still needto call DateTime.Parse (or preferrably DateTime.ParseExact) and catchthe potential exception, unless you want to do all the parsingcorrectly.Note that it also requires the leading zeroes for months and days - ifyou don''t want that, it becomes slightly trickier.(That only deals with dates in years 1000-2999; if you need to dealwith earlier or later years, change the 7th character inLowerBounds/UpperBounds.)Here''s a benchmark to compare the three approaches mentioned:using System;using System.Windows.Forms; // For MethodInvokerusing System.Text.RegularExpressions;using System.Globalization;delegate void DoSomething();class Test{static string[] invalid = {"123123", "wibble", "32/12/3223","14/23/1999", "04/35/1992", "02/29/2003"};static string[] valid = {"12/02/2321", "02/12/2312", "02/29/2004","01/30/2000"};const int Iterations = 100000;static void Main(){Time (new MethodInvoker(TestRegex));Time (new MethodInvoker(TestHardCoded));Time (new MethodInvoker(TestNoPreCheck));}static void Time(MethodInvoker test){DateTime start = DateTime.Now;test();DateTime end = DateTime.Now;Console.WriteLine ("{0}: {1}", test.Method.Name, end-start);}static readonly Regex Expression = new Regex(@"\d{1,2}\/\d{1,2}\/\d{4}", RegexOptions.Compiled);static void TestRegex(){for (int i=0; i < Iterations; i++){foreach (string x in invalid){if (Expression.IsMatch(x)){try{DateTime.ParseExact(x, "dd/mm/yyyy",CultureInfo.InvariantCulture);throw new Exception("Invalid date passed");}catch{}}}foreach (string x in valid){if (Expression.IsMatch(x)){try{DateTime.ParseExact(x, "dd/mm/yyyy",CultureInfo.InvariantCulture);}catch{throw new Exception("Valid date failed");}}elsethrow new Exception("Valid date failed");}}}static void TestHardCoded(){for (int i=0; i < Iterations; i++){foreach (string x in invalid){if (IsProbablyValidDate(x)){try{DateTime.ParseExact(x, "dd/mm/yyyy",CultureInfo.InvariantCulture);throw new Exception("Invalid date passed");}catch{}}}foreach (string x in valid){if (IsProbablyValidDate(x)){try{DateTime.ParseExact(x, "dd/mm/yyyy",CultureInfo.InvariantCulture);}catch{throw new Exception("Valid date failed");}}elsethrow new Exception("Valid date failed");}}}static void TestNoPreCheck(){for (int i=0; i < Iterations; i++){foreach (string x in invalid){try{DateTime.ParseExact(x, "dd/mm/yyyy",CultureInfo.InvariantCulture);throw new Exception("Invalid date passed");}catch{}}foreach (string x in valid){try{DateTime.ParseExact(x, "dd/mm/yyyy",CultureInfo.InvariantCulture);}catch{throw new Exception("Valid date failed");}}}}static readonly char[] LowerBounds = "00/00/1000".ToCharArray();static readonly char[] UpperBounds = "19/39/2999".ToCharArray();static bool IsProbablyValidDate(string date){if (date.Length != 10){return false;}for (int i=0; i < date.Length; i++){char c=date[i];if (c < LowerBounds[i] || c > UpperBounds[i]){return false;}}return true;}}The results on my laptop were:TestRegex: 00:00:09.3437500TestHardCoded: 00:00:04.3437500TestNoPreCheck: 00:00:12.5156250Changing the regex to require exactly two digits instead of 1 or 2 forthe month and day sped it up very slightly, but not reallysignificantly.--Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me tooHi Dan,Probably you are using C# because you write so nice your DateTme.Parse().However when you use VBNet you can use this. http://msdn.microsoft.com/library/de...afctisdate.aspCor My application asks the user to enter in a date - in the mm/dd/yyyyformat. Is there any quick and easy way to verify the date the user entersis formatted correctly? Right now I''m calling DateTime.Parse() and catchingthe FormatException but it seems this is a bit inefficient - catching theexception that is. There is some pretty obvious delay while it traces backup the call stack. Is there a better way? Something that returns a boolpossibly? 这篇关于检查DateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-12 05:39