正则表达式以验证时间戳

M.N*_*M.N 6 javascript regex validation timestamp

我需要一个正则表达式来验证格式的时间戳,使用Javascript:

YYYY/MM/DD HH:MI:SS

我尝试了一些烹饪,但似乎我的正则表达式技能无法覆盖某些东西.

请给我一个参考或方法来做到这一点.

PS:我提到正则表达式,仅作为建议.我使用Javascript并欢迎任何替代方案.

Tim*_*the 17

我建议使用Datejs.不需要自己解析日期,并且正则表达式不足以验证时间戳.使用datejs,您可以在日期中解析字符串,如果它无效,您将获得null:

Date.parse("2009/06/29 13:30:10", "yyyy/MM/dd HH:mm:ss");
Run Code Online (Sandbox Code Playgroud)


sou*_*rge 6

如果您只想验证语法,这里是POSIX正则表达式:

[0-9]{1,4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}
Run Code Online (Sandbox Code Playgroud)

但是如果你想检查语义,我会用您选择的语言处理字符串,有太多的情况你不能用正则表达式覆盖(如闰年/秒,夏令时等)

  • 根据您的需要,是的。但是您可以使用 {x} 代替 {x,x}。 (2认同)

Joe*_*oey 6

您应该考虑不使用正则表达式执行此操作,而是使用正确的格式字符串通过DateTime运行字符串.这样你就可以确保它确实是一个有效的时间戳,而不仅仅是看起来像它的东西.


Sté*_*ane 5

这是我今天早些时候编写的一个正则表达式,用于验证类似于您提到的格式的字符串:YYYY-MM-DD hh:mm:ss. 它不会识别一些不好的日期(例如,2 月 30 日),但可能比\d在每个位置使用简单化略好。注意事项:

  1. 您可以只指定一个日期、一个时间,或同时指定日期 + 时间
  2. 时间可以是 12 小时或 24 小时格式
  3. 秒是可选的
  4. 上午/下午是可选的

    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
    
    Run Code Online (Sandbox Code Playgroud)

@kyrias 的评论暗示,一旦我们到达 2020 年,这个正则表达式将在几个月内失败。根据您使用它的方式,您需要将“201[0-9]”更改为其他内容。

例如,如果您希望验证当前日期 +/- 几年,您可以将其更改为“20[12][0-9]”。要验证 2000 到 2099,请将其更改为“20[0-9]{2}”。

我已经更改了上面的原始正则表达式以查找 2010-2039。如有必要,其他人可以在 20 年内编辑此答案。