正则表达式验证正确的 ISO8601 日期字符串与时间 [英] Regex validate correct ISO8601 date string with time

查看:85
本文介绍了正则表达式验证正确的 ISO8601 日期字符串与时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:2015-01-17T18:23:02+00:00

在使用正则表达式时遇到了一些问题,因为字符串的某些部分被认为是有效"的,可能不是必需的.

此外,字符串可以格式化为:2015-01-17T18:23:02Z 有点让我失望

提前谢谢各位.

解决方案

基于

有点怪异,但它会检查有效日期,包括闰年(Proleptic Gregorian),有效对于 1000-9999 年,检查无效时间,如 25:30 或 21:94 和最大 UTC 偏移量 +/-19:59(或 Z).

(现在不会超过 +14:00 或 -12:00,但将来可能会发生).

完成:此答案仅支持基于 OP 给出的示例的 ISO8601 标准的一个子集.这是时间部分中的秒和 UTC 偏移量中的分钟的扩展符号.为简洁起见,它支持省略破折号和冒号的基本符号,或者省略UTC偏移量或最小单位中的分钟.也不支持序数日期(年中的某一天)或年-周-日-周表示法.

支持基本符号、序数和省略秒/UTC偏移分钟的正则表达式的扩展版本这里.

For example: 2015-01-17T18:23:02+00:00

Having some trouble with the regex as certain components of the string to be considered 'valid' are speculated and may not be required.

Also the fact the string can be formatted as: 2015-01-17T18:23:02Z is throwing me slightly

Thanks in advance guys.

解决方案

Based on an earlier answer of mine, you could do this and be pretty darn strict:

^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:Z|[+-][01]\d:[0-5]\d)$

Debuggex Demo

Slightly monstrous but it checks for valid dates including leap-year (Proleptic Gregorian), works for years 1000-9999, checks for invalid times like 25:30 or 21:94 and a maximum UTC offset of +/-19:59 (or a Z).

(right now more than +14:00 or -12:00 doesn't happen, but it might in the future).

For completion: This answer only supports a subset of the ISO8601 standard based on the examples OP gave. Which is the extended notation with seconds in the time section and minutes in the UTC offset. For brevity it does not support basic notation where dashes and colons are omitted, or the omitting of minutes in the UTC offset or the smallest unit. Nor is there support for ordinal dates (day-of-year) or year-week-dayofweek notations.

An extended version of the regex that supports basic notation, ordinal and the omitting of seconds / UTC-offset minutes lives here.

这篇关于正则表达式验证正确的 ISO8601 日期字符串与时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆