javascript regex iso datetime

前端 未结 9 1976
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 16:31

does anyone have a good regex pattern for matching iso datetimes?

ie: 2010-06-15T00:00:00

9条回答
  •  星月不相逢
    2020-12-02 16:56

    I have made this regex and solves the validation for dates as they come out of Javascript's .toISOString() method.

    ^[0-9]{4}-((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01])|(0[469]|11)-(0[1-9]|[12][0-9]|30)|(02)-(0[1-9]|[12][0-9]))T(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])\.[0-9]{3}Z$

    Contemplated:

    • Proper symbols ('-', 'T', ':', '.', 'Z') in proper places.
    • Consistency with months of 29, 30 or 31 days.
    • Hours from 00 to 23.
    • Minutes and seconds from 00 to 59.
    • Milliseconds from 000 to 999.

    Not contemplated:

    • Leap years.

    Example date: 2019-11-15T13:34:22.178Z

    Example to run directly in Chrome console: /^[0-9]{4}-((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01])|(0[469]|11)-(0[1-9]|[12][0-9]|30)|(02)-(0[1-9]|[12][0-9]))T(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])\.[0-9]{3}Z$/.test("2019-11-15T13:34:22.178Z");

    Regex flow diagram (Regexper):

提交回复
热议问题