Regular Expressions 101

Community Patterns

Community Library Entry

-18

Regular Expression
PCRE (PHP <7.3)

/
^(?<day>0[1-9]|1\d|2[1-8]|29(?=-\d{2}-(?!1[26]00|2[048]00)\d{2}(?:[02468][048]|[13579][26]))|30(?!-02)|31(?=-0[13578]|-1[02]))-(?<month>0[1-9]|1[0-2])-(?<year>[12]\d{3}) (?<hour>[01]\d|2[0-3]):(?<minute>[0-5]\d):(?<second>[0-5]\d)$
/
gm

Description

Validate Gregorian calendar dates that contain 24-hour times.

This will also correctly match the Feb 29 date when it falls on a valid leap year.

  • Leap years occur every 4 years, with one exception: when a year is evenly divisible by 100 but not evenly divisible by 400, the year will not be a leap year.
  • Thus years 2100, 2200, and 2300 are not leap years but years 2000, 2400, and 2800 are.
Submitted by Ka. - 11 years ago (Last modified a year ago)