【问题标题】:Conditional DateDiff条件日期差异
【发布时间】:2015-11-06 06:21:49
【问题描述】:

我访问了一些帖子,检索了 SO 中两个日期之间的日期差异,但它没有给我我正在寻找的答案。阅读文档也是如此,我在理解它的工作原理时遇到了问题。

我已尝试对其进行编码,但它的行为与我的预期不同。这是我的代码:

<?php
$currentDate = new DateTime();
$createDateJoin = date_create($getDate['date_joined']);
$dateJoin = date_format($createDateJoin, "Y-m-d");

$yearDifference = $currentDate->diff($createDateJoin);

  if ($yearDifference->d < 31 && $yearDifference->m = 0 && $yearDifference->y == 0) {
       echo $yearDifference->d . " days";
        } else if ($yearDifference->m > 3) {
              echo $yearDifference->m . " month";
        } else if ($yearDifference->y > 1) {
              echo $yearDifference->y . " years";
      } else {
              echo "Not yet assigned";
       }
 ?>

从我上面的代码中可以看出,在计算两个日期之间的差异后,我尝试进行打印,它满足 $yearDifference-&gt; 的条件。我所经历的程序的行为不打印相应地打印出我想要的东西(例如,工作超过 1 年的员工将打印出他们工作了多少年,新​​员工将打印出他们工作的年数,不到一个月的新员工将打印出天数)。

我想知道-&gt;d/m/y 是如何工作的,以及我如何才能真正利用dmy 来正确绘制具体日期。而且我还注意到,当我将$yearDifference 视为Stringint 时,会根据条件得出不同的结果。那么我应该怎样对待类型来更容易地操纵它呢?非常感谢您的帮助。

【问题讨论】:

    标签: php datediff


    【解决方案1】:

    您可以使用此代码获取不同方法 diff() 对象返回更多值的日期,以检查您可以 print_r 您的对象,该对象将打印通过 diff() 方法返回的所有数据成员

    <?php
    echo get_date_diff(strtotime('1990-10-12'),strtotime('2015-10-14'));
    function get_date_diff($date,$dateEnd) {
        $dStart = new DateTime(date("Y-m-d", $date));
        $dEnd = new DateTime(date("Y-m-d", $dateEnd));
        $dDiff = $dStart->diff($dEnd);
       return($dDiff->y.' years <br>'.$dDiff->m.' months <br>'.$dDiff->d. ' days');
    }
    
     ?> 
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2019-08-24
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多