Correct Regular expressions to match a date

后端 未结 11 641
不知归路
不知归路 2021-01-27 09:50

What is the correct regular expression to use to validate a date like. 2009-10-22 or 2009-01-01 etc. Platform PHP

相关标签:
11条回答
  • 2021-01-27 10:34

    OK, a regex that will validate month and day ranges could be

    [0-9]{4}-(?:1[0-2]|[1-9])-(?:3[01]|[12][0-9]|[1-9])
    

    If you want to restrict the years, say, from 1900 to 2050, you could end up with

    (?:2050|20[0-4][0-9]|19[0-9]{2})-(?:1[0-2]|[1-9])-(?:3[01]|[12][0-9]|[1-9])
    

    They will not catch "subtly wrong" dates like February 31st, so it's really quite clear that a sanity check needs to be performed outside of the regex.

    0 讨论(0)
  • 2021-01-27 10:35
     ^\d{4}-\d{2}-\d{2}$
    

    but no regular expression can prevent someone to enter "9867-39-56"

    0 讨论(0)
  • 2021-01-27 10:37

    If you can rely on more than a regular expression, an hybrid solution by using Posix functions date() and time() delivered with PHP could look like this:

    <?php
    date_default_timezone_set("GMT");
    
    function validateDate($date)
    {
        if (preg_match("^[0-9]{4}-[0-9]{2}-[0-9]{2}^", $date))
        {
            return date('Y-m-d', strtotime($date)) === $date;
        }
        return false;
    }
    
    // Some tests
    $dates = array(
        '2009-09-09', '2009-09-32', '2009-31-00', '2035-01-02',
    );
    foreach($dates AS $date)
    {
        echo $date .': '. (validateDate($date) ? 'OK' : 'FAILS') ."\n";
    }
    ?>
    

    It's not elegant plus you'll be limited by Unix Epoch time (from January 1 1970 00:00:00 GMT to January 19 2038 03:14:07 GMT), but it's reliable and it's well supported in PHP.

    0 讨论(0)
  • 2021-01-27 10:39

    In .NET Regex:

    \d{4}\-\d{2}\-\d{2}
    
    0 讨论(0)
  • 2021-01-27 10:41

    For a complete validation (which would include verifying that the day, month and year parts are valid) a Regex is not the tool of choice. Apart from month issues you'd get into trouble with leap years...

    So, if you just want to check if the rough format is correct, or isolate the different parts (year-month-day), a regex is fine.

    ([0-9]{1,4})-(1[012]|0?[1-9])-([12][0-9]|3[01]|0?[1-9])
    

    This is already pretty exact and captures the year (0..9999), month and day into capture groups, ready for parsing...

    0 讨论(0)
提交回复
热议问题