php日期比较方法


php date comparison methods

我需要帮助比较php中的两个日期。我比较的第一个日期是今天的日期,另一个来自数据库。我尝试过使用strtotime,但它只在数据库日期小于今天的日期时有效,如果日期大于今天的日期,我必须比较整个日期,而strtotime在这种情况下不起作用。

例如:

<?php
   $today=date('d/m/y');
   $expiry_date=$data['expiry'];
   if(strtotime($expiry_date)<strtotime($today)){ 
      echo "today is greater"; 
   } else {
       echo "expiry is greater";
       // only gives the right result when database result is smaller than today
   } 
?>

其他方法:

 $today=date('d/m/y');
   $expiry_date=$data['expiry'];
     if($expiry_date<$today)
       { echo "today is greater"; }
     else
       {echo "expiry is greater";} ?>`  // only gives the right result when database result is greater than today

第一种方法应该是正确的:

<?php
   $today=date('d/m/y');
   $expiry_date=$data['expiry'];
   if(strtotime($expiry_date)<strtotime($today)){ 
      echo "today is greater"; 
   } else {
       echo "expiry is greater";
       // only gives the right result when database result is smaller than today
   } 
?>

第二个是比较两个字符串,但这是一个数值问题。strtotime函数将字符串转换为可以比较的数字时间。这个SO问题展示了很多例子。将给定日期与今天进行比较

如果您获取每个变量并执行var_dump,您可以看到正在进行比较的内容。这里有一个例子:

我手动设置$expiry_date,因为我们不知道它是以什么格式检索的。

   $data['expiry'] = '11/12/10';
   var_dump($today, $expiry_date);
   var_dump(strtotime($today), strtotime($expiry_date));
   var_dump($today, strtotime($expiry_date));

结果:

string(8) "08/09/14" string(8) "11/12/10" 
int(1407567600) int(1289548800) 
string(8) "08/09/14" int(1289548800)

我认为这里最重要的部分是弄清楚从数据库中检索到的内容以及格式。首先var_dump变量$expiry_date,而不将其修改为strtotime。如果格式是关闭的,即使只有破折号或点而不是斜线,你会得到不同的结果。这是sam在frontiermedia dot net dot au 的strtotime手册中显示的

<?php 
echo date("jS F, Y", strtotime("11.12.10")); 
// outputs 10th December, 2011 
echo date("jS F, Y", strtotime("11/12/10")); 
// outputs 12th November, 2010 
echo date("jS F, Y", strtotime("11-12-10")); 
// outputs 11th December, 2010  
?> 

然后根据需要将其转换为类似于今天的日期变量('d/m/y'),然后将两者转换为strtotime并进行比较。

确保您的今天日期格式和数据库日期格式相同。。。

$today=date('dd/mm/yyyy'); // DD/MM/YYYY (you are using d/m/y here )
$expiry_date="05/10/2014"; // $data['expiry']; DD/MM/YYYY Make sure for this format also
        if(strtotime($expiry_date)<strtotime($today)){
            echo "today is greater";
        } else {
            echo "expiry is greater";
            // only gives the right result when database result is smaller than today
        }