Regular Expression to validate a timestamp

后端 未结 13 683
名媛妹妹
名媛妹妹 2021-01-01 01:19

I need a regular expression to validate a timestamp of the format, using Javascript:

YYYY/MM/DD HH:MI:SS

I trie

13条回答
  •  星月不相逢
    2021-01-01 01:44

    Here is how I build up a regex matching exactly SQL Timestamp yyyy-mm-dd hh:mm:ss in the range [1970-01-01 00:00:00, 2037-12-31 23:59:59]

    $leapYear = "(19[79][26]|198[048]|20[02][048]|20[13][26])";
    $leapDate = "$leapYear-02-29";
    
    $regularYear = "(19[789][0-9]|20[012][0-9]|203[0-7])";
    $regularFebruaryDate = "02-([01][1-9]|2[0-8])";
    $month31Date = "(0[13578]|10|12)-([012][1-9]|3[01])";
    $month30Date = "(0[469]|11)-([012][1-9]|30)";
    $regularDate = "$regularYear-($regularFebruaryDate|$month30Date|$month31Date)";
    
    $hours = "(2[0-3]|[01][0-9])";
    $minutes = "[0-5][0-9]";
    $seconds = "[0-5][0-9]";
    
    $sqlTimestamp = "($leapDate|$regularDate) $hours:$minutes:$seconds";
    

    Note: I avoided the year 2038 to have one less edge-case. The max possible SQL timestamp is 2038-01-19 03:14:07.

提交回复
热议问题