PHP - 比较数据库日期时间与当前日期时间

3

我在StackOverflow上看到了几种不同的DateTime比较方法,但似乎都无法正确实现。我需要能够从数据库中检索一行数据,将DateTime与当前时间进行比较,然后评估它是否已过期。

在这种情况下,我需要检查当前行是否已过期。

if (strtotime(new DateTime()) > strtotime($row['expiration_date'])) {
  $response = 'Valid Coupon!';
} else {
  $response = 'Coupon Expired';
}

我尝试了几种不同的方法,但似乎都不能正常工作。

"2017-07-15 13:42:31 > 2017-07-15 14:27:31"
// and 
"2017-07-15 13:42:31 > 2017-07-14 13:03:04"

两者都返回有效的优惠券。

我尝试了很多方法,但似乎无法弄清楚为什么这些日期无法正常工作。有什么想法吗?

2个回答

10

使用 ->format

 if (strtotime((new DateTime())->format("Y-m-d H:i:s")) > strtotime($row['expiration_date'])) {
   $response = 'Valid Coupon!';
 } else {
    $response = 'Coupon Expired';
 }

请查看此实时示例:https://eval.in/833030

或者您可以使用

   (new DateTime())->getTimestamp();

不是

   strtotime((new DateTime())->format("Y-m-d H:i:s"));

请查看:https://eval.in/833038


2

您应该将new DateTime()和过期日期和时间转换为Unix时间戳。

当您将日期转换为Unix时间戳时,它将以数字格式显示。这样,您就可以比较您的值。

例如:

$current_date = strtotime(new DateTime); //your current date and time 
$expatriation_date = strtotime($row['expiration_date']);  //your database data and time values // 
if($current_date > expatriation_date ){
    $response = 'Valid Coupon!';              
}
else{
    $response = 'Coupon Expired';
}

您当前的Unix时间戳为"1500118951",到期时间的Unix时间戳为"1500121651"。您可以轻松比较您的数值。


1
不,我认为不是。因为这是一种找到解决方案的简单方法。我以前也用过这种技巧。 - Farhan Ghaffar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接