Is there a faster way to check if this is a valid

2020-08-12 18:31发布

Is there a faster way then to simply catch an exception like below?

try
{
    date = new DateTime(model_.Date.Year, model_.Date.Month, (7 * multiplier) + (7 - dow) + 2);
}
catch (Exception)
{
    // This is an invalid date
}

9条回答
Summer. ? 凉城
2楼-- · 2020-08-12 18:34
String DateString = String.Format("{0}/{1}/{2}", model_.Date.Month, (7 * multiplier) + (7 - dow) + 2),model_.Date.Year);

DateTime dateTime;
if(DateTime.TryParse(DateString, out dateTime))
{
    // valid
}

As the comment pointed out by GenericTypeTea, this code will not run any faster than what you have now. However, I believe you gain in readability.

查看更多
不美不萌又怎样
3楼-- · 2020-08-12 18:34

The fastest way to validate a date is an one-liner:

static bool IsValidDate(int year, int month, int day) =>
             !(year < 1 || year > 9999 ||
            month < 1 || month > 12 ||
            day < 1 || day > DateTime.DaysInMonth(year, month));

Using a DateTime constructor or any parse function or any exception handler will slow down the validation. TryParse is preferred only if you want to validate a string.

查看更多
4楼-- · 2020-08-12 18:38

Look at the DateTime.TryParse method

查看更多
\"骚年 ilove
5楼-- · 2020-08-12 18:40

Hmm... think of it this way: the model_ class has a DateTime property

model_.Date

, so no need to validate the year & month. The only tricky part is the day of the month:

(7 * multiplier) + (7 - dow) + 2

So a very quick and efficient way to validate this (which is better than throwing and catching) is to use the DateTime.DaysInMonth method:

if ((multiplier <= 4) && 
    (DateTime.DaysInMonth(model_.Date.Year, model_.Date.Month) < 
        (7 * multiplier) + (7 - dow) + 2))
{
    // error: invalid days for the month/year combo...
}

Another benefit is that you don't need to instantiate a new DateTime just to validate this information.

P.S. Updated the code to ensure that multiplier is <= 4. That only makes sense, since any value >=5 will fail the DaysInMonth test...

查看更多
啃猪蹄的小仙女
6楼-- · 2020-08-12 18:42

One thing though: Exceptions are for exceptional cases. Bogoformatted strings are not exceptional but expected, so TryParse is more appropriate.

Using try/catch for checking validness is misuse and misconception of exceptions, especially with a catch-all catch (the latter already caused me searching for hours for why something doesn't work, and that many times).

查看更多
Rolldiameter
7楼-- · 2020-08-12 18:44

I don't know about faster, but

DateTime.TryParse()

Should do the same thing.

I'd be interested if anyone can tell me if this is faster (in terms of processor time) than the way described in the question.

查看更多
登录 后发表回答