Regular Expression to validate a timestamp

后端 未结 13 553
名媛妹妹
名媛妹妹 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 02:04

    Here is a regex I wrote earlier today for validating strings in a format similar to what you mentioned: YYYY-MM-DD hh:mm:ss. It does not identify some bad dates (for example, February 30th) but may be slightly better than using the simplistic \d at each position. Things to note:

    1. you can specify just a date, just a time, or both date + time
    2. time can be in 12-hour or 24-hour format
    3. seconds are optional
    4. am/pm is optional

      const std::string dateAndTimeRegex =
          "^\\s*"                     // ignore whitespace
          "("                         // start of date
              "20[123][0-9]"          // year: 2010, 2011, ..., through 2039
              "\\W"                   // delimiter between year and month; typically will be "-"
              "([0]?[0-9]|1[012])"    // month: 0 through 9, or 00 through 09, or 10 through 12
              "\\W"                   // delimiter between month and day; typically will be "-"
              "([012]?[0-9]|3[01])"   // day: 0 through 9, or 00 through 29, or 30, or 31
          ")?"                        // end of optional date
          "\\s?"                      // optional whitespace
          "("                         // start of time
              "([01]?[0-9]|2[0-3])"   // hour: 0 through 9, or 00 through 19, or 20 through 23
              "\\W"                   // delimiter between hours and minutes; typically will be ":"
              "([0-5][0-9])"          // minute: 00 through 59
              "("                     // start of seconds (optional)
                  "\\W"               // delimiter between minutes and seconds; typically will be ":"
                  "([0-5][0-9])"      // seconds: 00 through 59
              ")?"                    // end of optional seconds
              "(\\s*[AaPp][Mm])?"     // optional AM, am, PM, pm
          ")?"                        // end of optional time
          "\\s*$";                    // trailing whitespace
      

    A comment from @kyrias hints that this regex will fail in a few months once we hit the year 2020. Depending on how you use it, you'll need to change "201[0-9]" to something else.

    For example, if you are looking to validate the current date +/- a few years, you could change it to "20[12][0-9]". To validate 2000 through 2099, change it to "20[0-9]{2}".

    I've changed the original regex above to look for 2010-2039. Someone else can edit this answer in 20 years if necessary.

提交回复
热议问题