strtotime 日期验证通过无效日期
我正在设置一个基本的 CMS,允许客户将文章添加到他们的移动应用程序中。 CMS 采用 PHP 编码,并将使用 JSON 将内容传送到移动应用程序。
现在我的问题是可以选择在特定日期发布文章,因此我想验证该日期以检查其是否有效。
因此,为了测试可能性,我制作了一个小脚本。我使用 strtotime()
来检查日期是否有效,我的脚本是:
<?php
$date[] = '2011-31-01';
$date[] = '2011-02-31';
foreach($date as $str) {
if(strtotime($str) == false) {
$result[] = '<p>[' . $str . '] Resulted in an <span style="color: red;">Error.</span></p>';
} else {
$result[] = '<p>[' . $str . '] Resulted in <span style="color: green;">Success.</span></p>';
}
}
foreach($result as $return) {
echo $return;
}
?>
现在我的问题是日期 2011-02-31
,即 2011 年 2 月 31 日
返回有效,但显然不是。所以我的问题是它为什么这样做?有没有更好的方法来检查日期是否有效且存在?
提前致谢。
I am in the middle of setting up a basic CMS that allows the client to add articles to their mobile app. The CMS is coded in PHP and will use JSON to deliver the content to the mobile app.
Now my problem is there is an option to publish the article at a certain date, so I want to validate the date to check it is valid.
So to test possibilites I made a small script. I am using strtotime()
to check the date is valid, my script is:
<?php
$date[] = '2011-31-01';
$date[] = '2011-02-31';
foreach($date as $str) {
if(strtotime($str) == false) {
$result[] = '<p>[' . $str . '] Resulted in an <span style="color: red;">Error.</span></p>';
} else {
$result[] = '<p>[' . $str . '] Resulted in <span style="color: green;">Success.</span></p>';
}
}
foreach($result as $return) {
echo $return;
}
?>
Now my problem is the date 2011-02-31
which is 31st February 2011
is returning as valid, when obviously it isn't. So my question is why does it do this? and is there a better method to check that the date is valid and exists?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
checkdate();
验证公历日期。如果给定的日期有效,则返回 TRUE;否则返回 FALSE。它返回错误!
这就是要走的路。
checkdate();
Validates a Gregorian date. Returns TRUE if the date given is valid; otherwise returns FALSE.It returns false!
That's the way to go.
除非您的日期字符串有一个(或一小组)固定格式,否则很难获得可接受的结果。如果您知道格式,您可以直接自己解析字符串(然后使用
checkdate
进行测试),或者使用strptime
尝试根据已知格式进行解析,直到获得有效结果。如果您不知道格式,并且必须使用
strtotime
,那么您需要接受strtotime
将尝试以最佳方式解析日期字符串。这可能会导致日期与预期不同。Unless you have one (or a small set) fixed format for your date string it will be hard to get an acceptable result. In case you know the format, you can either parse the string directly yourself (and test it afterwards with
checkdate
), or you usestrptime
to try parsing against known formats until you get a valid result.If you don’t know the format, and you have to use
strtotime
, then you are required to accept thatstrtotime
will try parsing the date string in the best possible way. This may lead to different dates than it was expected to be.