开发者

C#. Validation of date pattern

In my application user can specify the pattern for dates by entering it in the textbox. This pattern is used for logging messages. For example, if user specify 'dd-MM' then in the l开发者_如何学Pythonog file he could see following:

[12-06] Some message...
[02-09] Some message 2...

How to validate this pattern? How to protect entering wrong patterns?


The easiest way is to just try and parse the date.

DateTime someDate;

// Valid will be false if it could not parse the date
bool valid = DateTime.TryParse(yourFormat, out someDate);


Regular Expressions will probably be a good choice.


You can take a look at Regular Expressions or else, at this question


This is a difficult problem. I tried:

try
{
    DateTime.Now.ToString(tmpFormatSpec);                    
}
catch (Exception)
{
    // the format spec is known to be bad
}

The problem is that date format patterns are SO flexible. Even things that don't render date information are allowed (and are not detected by my sample code):

DateTime.Now.ToString("bla");  // no exception raised

See this other SO post for an even better way (I haven't tried it yet).

Also see this discussion about the problem, with comments by J. Skeet.


This is a difficult problem. I tried:

try
{
    DateTime.Now.ToString(tmpFormatSpec);                    
}
catch (Exception)
{
    // the format spec is known to be bad
}

The problem is that date format patterns are SO flexible. Even things that don't render date information are allowed (and are not detected by my sample code):

DateTime.Now.ToString("bla");  // no exception raised

See this other SO post for an even better way (I haven't tried it yet).

Also see this discussion about the problem, with comments by J. Skeet.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜