[英]PHP date comparison and strtotime
使用XAMPP 5.6.8的WIndows,我正在用HTML和PHP构建一个简单的Web应用程序。
我想将从数据库中检索到的日期与今天的日期进行比较。
我有一个可以成功返回字符串值(英国日期格式dmy
)的函数。
到目前为止,我的代码是;
$expDate = get_api_data($id); // returns a string
var_dump($expDate); // this prints string(8) "31-12-19"
使用这个$expDate
值,我想实现类似的效果;
if (strtotime('d-m-y', $expDate) > time()) { // if date > than today
echo 'date is greater than today';
}
elseif (strtotime('d-m-y', $expDate) < time()) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
目前,我收到的日期比今天少 -即使日期是31-12-19
。 我不确定我是否采用正确的方法?
任何帮助将不胜感激,因为我一直花大量时间研究无济于事的答案。
执行您的代码时出现此错误
PHP注意:遇到格式不正确的数值
您应该查看该文档以充分利用此功能: http : //php.net/manual/fr/function.strtotime.php
第一个参数应该是时间,而不是格式。
顺便说一句,我更喜欢使用DateTime类比较日期,您可以执行以下操作:
<?php
$expectedDate = \DateTime::createFromFormat('d-m-y', get_api_data($id));
$nowDate = new \DateTime();
if ($expectedDate > $nowDate) { // if date > than today
echo 'date is greater than today';
}
elseif ($expectedDate < $nowDate) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
$formattedDate = DateTime::createFromFormat('d-m-y', $expDate);
$expDate= $formattedDate->getTimestamp();
if ($expDate > time()) { // if date > than today
echo 'date is greater than today';
.....
尝试上面的代码示例,如果您具有PHP 5.2.0或更高版本,请尝试使用DateTime类http://php.net/manual/zh/datetime.createfromformat.php 。 然后使用该dateTime对象,您可以按照自己想要的方式进行比较,例如,在我的示例中,我正在按时间进行操作。
您的代码将显示一个通知。 如果打开php错误报告,您将观察它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.