PHP日期比较和strtotime

时间:2016-10-04 14:54:07

标签: php date datetime strtotime

使用WIndows,XAMPP 5.6.8我正在用HTML和PHP构建一个简单的Web应用程序。

我想将从数据库中检索到的日期与今天的日期进行比较。

我有一个成功返回字符串值的函数(采用英国日期格式d-m-y)。

到目前为止我的代码是;

$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。我不确定我是否正确接近这个?

任何帮助都会非常感激,因为我已经花了很多时间研究答案而无济于事。

2 个答案:

答案 0 :(得分:2)

执行代码时出现此错误

  

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';
  }

答案 1 :(得分:0)

$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或更高版本http://php.net/manual/en/datetime.createfromformat.php,请尝试使用DateTime类。然后使用该dateTime对象,您可以以您想要的方式进行比较,例如在我的样本中,我正在按时完成。

您的代码会显示通知。如果你打开php错误报告,你会观察它。