验证 ISO 8601 日期字符串
如何验证 ISO 8601 日期字符串(例如:2011-10-02T23:25:42Z)。
我知道 ISO 8601 日期有几种可能的表示形式,但我只对验证上面作为示例给出的格式感兴趣。
How do you validate ISO 8601 date string (ex: 2011-10-02T23:25:42Z).
I know that there are several possible representations of ISO 8601 dates, but I'm only interested in validating the format I gave as an example above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我想分享我的轻量级解决方案。这并不理想,但可能对某人有帮助。
注意!
某些有效的 ISO8601 日期将失败请查看下面的列表
I want to share my lightweight solution. It is not ideal, but might be helpful for someone.
Atention!
Some valid ISO8601 dates will fail Look at the list below
这对我有用,它使用正则表达式来确保日期采用您想要的格式,然后尝试解析日期并重新创建它以确保输出与输入匹配:
您可以进一步扩展以使用 checkdate 以确保月日和年份也有效。
This worked for me, it uses a regular expression to make sure the date is in the format you want, and then tries to parse the date and recreate it to make sure the output matches the input:
You could expand further to use checkdate to make sure the month day and year are valid as well.
编辑:到目前为止,最简单的方法是简单地尝试使用字符串创建
DateTime
对象,例如,如果
DateTime
构造函数无法解析字符串,它会抛出异常,例如请注意,如果您省略时区指示符,它将使用配置的默认时区。
第二个最简单的方法是使用正则表达式。像这样的东西可以覆盖它
Edit: By far the easiest method is to simply try to create a
DateTime
object using the string, egIf the
DateTime
constructor cannot parse the string, it will throw an exception, egNote that if you leave off the time zone designator, it will use the configured default timezone.
Second easiest method is to use a regular expression. Something like this aught to cover it
请参阅http://www .pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/。它提供了这个正则表达式来使用:
我想这并不能准确回答你的问题,因为它会匹配任何有效的 ISO 8601 日期,但如果没问题的话,那么它就可以完美工作。
See http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/. It gives this regex to use:
I suppose this does not answer your question exactly, since it will match any valid ISO 8601 date, but if that is alright then this works perfectly.
这是我使用的功能。它类似于draw010的答案,但也适用于以“+01:00”或“-01:00”结尾的时间戳。
This is the function I use. It is similar to the answer of drew010 but works also for timestamps ending with "+01:00" or "-01:00".
Carbon 很好地处理了这部分,
您也可以对 DateTime 做同样的事情
Carbon is handling this part really well
You may do the same with DateTime