Regular Expression to match a valid day in a date

后端 未结 10 1767
别那么骄傲
别那么骄傲 2020-12-11 01:45

I need help coming up with a regex to make sure the user enters a valid date The string will be in the format of mm/dd/yyyy

Here is what I have come up

10条回答
  •  青春惊慌失措
    2020-12-11 02:23

    use DateTime;
    

    Other solutions are fine, probably work, etc. Usually, you end up wanting to do a bit more, and then a bit more, and eventually you have some crazy code, and leap years, and why are you doing it yourself again?

    DateTime and its formatters are your solution. Use them! Sometimes they are a bit overkill, but often that works out for you down the road.

    my $dayFormat = new DateTime::Format::Strptime(pattern => '%d/%m/%Y');
    my $foo = $dayFormat->parse_datetime($myDateString);
    

    $foo is now a DateTime object. Enjoy.

    If your date string wasn't properly formatted, $foo will be "undef" and $dayFormat->errstr will tell you why.

提交回复
热议问题