且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

出生日期应为DD-MM-YYYY格式,出生日期不应为

更新时间:2023-01-29 10:47:20

不要尝试使用正则表达式:它们是文本处理器,并且正确验证日期是一个真正的痛苦:例如,想想闰年。



相反,使用DateTime.TryParseExact - 如果它工作,它甚至会为您提供检查日期在范围内所需的数据:

Don't try to use a Regex: they are Text processors, and to validate a date correctly is a real pain: think about leap years for example.

Instead, use DateTime.TryParseExact - if it works it even gives you the data you need to check the date is in range:
DateTime dtBirth;
if (DateTime.TryParseExact(input, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dtBirth))
    {
    if (dtBirth < DateTime.Now.Date)
        {
        ...
        }
    }


string input ="12-12-2014";
DateTime dt;
if (DateTime.TryParseExact( input, "dd-MM-yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None, out dt)
        && dt < DateTime.Now)
{
    //validation success
}


日期是日期,没有别的,无论是什么显示格式!



您不需要任何正则表达式。您需要将文本转换为 DateTime [ ^ 。请参阅Solution1或Solution2。
Date is date and nothing else, no matter of displayed format!

You don't need any regular expression. You need to convert text into DateTime[^]. Please, see Solution1 or Solution2.