Regex to validate date format dd/mm/yyyy

后端 未结 21 2513
挽巷
挽巷 2020-11-21 06:32

I need to validate a date string for the format dd/mm/yyyy with a regular expresssion.

This regex validates dd/mm/yyyy, but not the invalid

21条回答
  •  盖世英雄少女心
    2020-11-21 07:16

    I suspect that the following is as accurate as can be expected without knowing when the user's locale switched over from the Julian to the Gregorian calendars.

    It accepts either '-', '/', or nothing as separators between year, month, and day, no matter the order.

    MMddyyyy:

    ^(((0[13-9]|1[012])[-/]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-/]?31|02[-/]?(0[1-9]|1[0-9]|2[0-8]))[-/]?[0-9]{4}|02[-/]?29[-/]?([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00))$
    

    ddMMyyyy:

    ^(((0[1-9]|[12][0-9]|30)[-/]?(0[13-9]|1[012])|31[-/]?(0[13578]|1[02])|(0[1-9]|1[0-9]|2[0-8])[-/]?02)[-/]?[0-9]{4}|29[-/]?02[-/]?([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00))$
    

    yyyyMMdd:

    ^([0-9]{4}[-/]?((0[13-9]|1[012])[-/]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-/]?31|02[-/]?(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00)[-/]?02[-/]?29)$
    

    Other than order, these all are accurate to the Julian Calendar (leap year every four years) until 1700, when the Gregorian Calendar diverges from the Julian. It has two issues:

    1. It accepts the year 0000, which doesn't exist in many, but not all, standards. Note that ISO 8601 does accept year 0000 (equivalent to 1 BCE).
    2. It doesn't skip the 10-13 days which were lost when the Gregorian Calendar came into use. This varies by locality though. For example, the Roman Catholic Church skipped 10 days, October 5th through October 14th, 1582, but Greece (the last to switch) skipped February 16th through the 28th of 1923, 13 days, having to take into account the leap years of 1700, 1800, and 1900.

    This has been tested against Java's calendar implementation from the year 0001 until the year 9999 with the only discrepancy being the abovementioned 10 days in 1582.

提交回复
热议问题