如何在 PHP 中检查字符串的日期格式?
我想检查字符串是否具有这种时间格式:
Y-m-d H:i:s
如果没有,则执行一些代码,例如
if here will be condition do { this }
else do { this }
如何在 PHP 中执行此条件?
I would like to check if the string has this time format:
Y-m-d H:i:s
and if not than do some code e.g.
if here will be condition do { this }
else do { this }
How to do this condition in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
preg_match
是您正在寻找的内容,具体来说:如果您真的只想要正确格式化的日期,那么
preg_match
is what you are looking for, specifically:if you REALLY ONLY want properly formatted date, then
如何在 PHP 中检查字符串的日期格式?
How to check string's date format in PHP?
你不知道。无法判断它是
Ymd
还是Ydm
,甚至是Ydd
与Ymm
。2012-05-12
是什么? 5月12日还是12月5日?但是,如果您对此感到满意,您始终可以这样做:
尽管您可能想看看
preg_match('/\d{4}-\d{2}-\d{2} \d{2} :\d{2}:\d{2}/',$date)
在此方面速度并不快。还没有测试过。You don't. It is impossible to tell if it is
Y-m-d
orY-d-m
, or evenY-d-d
vsY-m-m
. What is2012-05-12
? May 12th or Dec. 5?But, if you are content with that, you can always do:
Though you might want to see if
preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date)
isn't faster on this. Haven't tested it.请注意,这仅检查日期字符串是否看起来像一串由冒号和破折号分隔的数字。它不会检查诸如“2011-02-31”(2 月 31 日)或“99:99:99”一段时间(99 点?)之类的奇怪现象。
Note that this only checks that the date string looks like a bunch of digits separated by colons and dashes. It does NOT check for oddities like '2011-02-31' (Feb 31st) or '99:99:99' for a time (99 o'clock?).
来自 php.net
这里有一个很酷的函数来验证 mysql 日期时间:
From php.net
here's a cool function to validate a mysql datetime:
你总是可以强制它:
You could always just force it:
答案可能涉及正则表达式。我建议您阅读本文档,如果仍有问题,请返回此处。
The answer probably involves regular expressions. I suggest reading this documentation, and then coming back here if you're still having trouble.